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!