0

I have this code where I recursively list all the files from a folder. My question is how to print the output from the console to a .txt file? It would help me a lot if someone could add what is needed in my code.

import java.io.*;

public class Exp {

    public static void main(String[] args) throws IOException {
        File f = new File("C:\\Users\\User\\Downloads");
        rec(f);
    }

    public static void rec(File file) throws FileNotFoundException {
        File[] list = file.listFiles();

        for (File f : list) {
            if (f.isFile()) {
                System.out.println(f.getName());
            }

            else if (f.isDirectory()) {
                rec(f);
            }

        }
    }
}
kazioX
  • 3
  • 2
  • Possible duplicate of [How do I create a file and write to it in Java?](https://stackoverflow.com/questions/2885173/how-do-i-create-a-file-and-write-to-it-in-java) – Thiyagu Sep 06 '18 at 17:08

1 Answers1

0

You are currently outputting to System.out, which is a PrintStream. Instead of doing that, create a PrintStream for a .txt file and pass the PrintStream as an argument to your rec method. Use the try-with-resources idiom to ensure the PrintStream gets closed when you're done with it.

DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42