简体   繁体   English

用递归方法写入文件

[英]Writing to a file in a recursive method

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. 显然, resultList是每个目录,因此效果不好。

So I tried to replace the System.out... into a file with PrintWriter * ( writer.println(file.toString()); ) but it left an empty output file. 因此,我尝试将System.out...替换为带有PrintWriter *( writer.println(file.toString()); )的文件,但它留下了一个空的输出文件。

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. 我以为这是因为最初我没有关闭writer但是由于递归,我在哪里做都没关系。 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. 我尝试改为附加到StringBuilder (+新行),然后将其添加到一个文件中,但又一次留下一个空白文件。

So basically, my question is: How can I add each entry in the nested if into a text file (ie the output of System.out.println(file.toString()); ) 所以基本上,我的问题是:我如何添加的每个条目在嵌套if到一个文本文件(即输出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! 我最初是使用递归方法初始化PrintWriter ,所以最终在每个目录和每个子目录中创建一个文件-糟糕!

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. 请注意, java.io.file.File是用于处理文件的旧API。
You should use java.io API that provides more reliable, simple and efficient way to manipulate files. 您应该使用java.io API,该API提供了更可靠,简单和有效的方式来处理文件。
@crizzis refers it in its comment and he/she is right. @crizzis在评论中引用了它,他/她是正确的。
But you don't really need to create an FileVisitor implementation for such a simple case. 但是您实际上不需要为这种简单情况创建FileVisitor实现。

Here is an example relying on Path and Files.walk() . 这是一个依赖PathFiles.walk()的示例。
The processing is performed by two Stream functions : 该处理由两个Stream函数执行:

  • filter empty directory (intermediary operation) 过滤空目录(中间操作)
  • for each : print the directory path in the writer (terminal operation) 对于每个:在writer中打印目录路径(终端操作)

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();
                     }
                 });
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM