0

I'm trying to put all the Strings in my print statement below into a file.

I have a recursive method to check all directories, and sub-directories (which I think it was here I took code from).

Then it basically checks if the directory is empty, and if so, print the directory name:

File directory = new File(directoryName);
List<File> resultList = new ArrayList<>();
File[] fList = directory.listFiles();
resultList.addAll(Arrays.asList(fList));
for (File file : fList) {
    if (file.isDirectory()) {
        if (file.list().length == 0) {
            System.out.println(file.toString());
        }
        resultList.addAll(listf(file.getAbsolutePath()));
    }
}
return resultList;

Obviously, resultList is every directory so that's no good.

So I tried to replace the System.out... into a file with PrintWriter* (writer.println(file.toString());) but it left an empty output file.

I thought this was because I didn't initially close the writer but it seemed to not matter where I did this, because of the recursion. I tried instead to append to a StringBuilder (+ a new line) and then add that in one go to a file but that again just left a blank file.

So basically, my question is: How can I add each entry in the nested if into a text file (i.e. the output of System.out.println(file.toString());)

I initially had initialised the PrintWriter in the recursive method so ended up creating a file in every directory and every subdirectory - oops!

achAmháin
  • 4,176
  • 4
  • 17
  • 40
  • 2
    "`resultList` is every directory so that's no good." - does it have to be? Why don't you just collect empty directories? – Thomas Jan 19 '18 at 15:59
  • 2
    The question you referenced is four years old. Do yourself a favor and use a file visitor: https://docs.oracle.com/javase/tutorial/essential/io/walk.html – crizzis Jan 19 '18 at 16:00
  • 2
    "I tried instead to append to a StringBuilder (+ a new line) and then add that in one go to a file but that again just left a blank file." - did you check the contents of that StringBuilder? If it wasn't empty your problem isn't recursion but how you write to the file - which you didn't show. – Thomas Jan 19 '18 at 16:01
  • Yes - I guess collecting and returning empty directories would work - I'll give it a go later on when I get chance. True - I thought it was an old version as it was on my machine for a while so I just amended it slightly for my purpose; I'll have a look at up-to-date software. And, no the StringBuilder was not empty with a print statement, but the file contents were. Thanks all anyway; I might try a new solution with file visitor as mentioned above and see how I fare. – achAmháin Jan 19 '18 at 16:19

1 Answers1

1

It left a blank file.

To avoid that, you can enable the auto flush by using this overloaded constructor :

public PrintWriter(OutputStream out, boolean autoFlush) 

Or you can also flush the writer before the program is terminated.

Note that java.io.file.File is an old API to manipulate files.
You should use java.io API that provides more reliable, simple and efficient way to manipulate files.
@crizzis refers it in its comment and he/she is right.
But you don't really need to create an FileVisitor implementation for such a simple case.

Here is an example relying on Path and Files.walk() .
The processing is performed by two Stream functions :

  • filter empty directory (intermediary operation)
  • for each : print the directory path in the writer (terminal operation)

Here is a full executable code (exception cases are not exhaustively handled. You have to do it in a more complete way according to your requirements):

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WriterForEmptyDirectory {

    public static void main(String[] args) throws IOException {
        try (PrintWriter writer = new PrintWriter(new BufferedOutputStream(new FileOutputStream("result")), true)) {

            String directoryPath = "a-path-to-analyse";
            Files.walk(Paths.get(directoryPath))
                 .filter(f -> {
                     try {
                         return Files.isDirectory(f) && Files.list(f)
                                                             .count() == 0;
                     } catch (IOException e) {
                         System.err.println("Error to handle for file " + f);
                         e.printStackTrace();
                         return false;
                     }
                 })
                 .forEach(f -> {
                     try {
                         writer.println(f);
                     } catch (Exception e) {
                         System.err.println("Error to handle for file " + f);
                         e.printStackTrace();
                     }
                 });
        }
    }
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215