S
S
SoloCheater2018-08-08 17:00:21
Java
SoloCheater, 2018-08-08 17:00:21

How to get a list of all files in subdirectories under a certain path (this task is done) and how to write the results to a txt file?

Hello. I am writing a program in java. "How to get a list of all files in subdirectories in a specific path" - this task has already been completed. Output code for all files:

public static void main(String[] args) throws IOException, InterruptedException {
    	
    	displayAll(new File("D:\\GamersDesktop"));
    	   
    }
    
    public static void displayAll(File path){      
        if(path.isFile()){
            System.out.println(path.getAbsolutePath());
        }else{
            System.out.println(path.getAbsolutePath());         
            File files[] = path.listFiles();
            for(File dirOrFile: files){
                displayAll(dirOrFile);
            }
        }
    }

Now the question is: write the result of this function displayAll(new File("D:\\GamersDesktop")); to a txt file?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kastian, 2018-08-16
@iSmoke

public static void main(String[] args) throws IOException {
        
        FileWriter writer = new FileWriter(new File("D://result.txt"));
        displayAll(new File("D:\\Archive"), writer);
        writer.close();
    }
    
    public static void displayAll(File path, FileWriter writer) throws IOException {
        if(path.isFile()){
            writer.write(path.getAbsolutePath()+"\n");
        }else{
            writer.write(path.getAbsolutePath()+"\n");
            File files[] = path.listFiles();
            for(File dirOrFile: files){
                displayAll(dirOrFile, writer);
            }
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question