Java next line print.writer



>我将文件列表保存到文件时遇到了一点问题:

class listFilesForFolder{
    static String fs1= System.getProperty("user.dir" )+"/lista plików";
    static File fs2= new File(fs1);
    public static void listFilesForFolder(File folder) throws FileNotFoundException  {

        for ( File fileEntry : folder.listFiles()) {   
            if (fileEntry.isDirectory()) {
                listFilesForFolder(fileEntry);
            }
            System.out.println(fileEntry.getName());
            zapis(fileEntry.getName());
         }
    }
    static void zapis(String plik)throws FileNotFoundException {
        PrintWriter zapis = new PrintWriter(fs2);
        zapis.println(plik+ "rn");
        zapis.close();
    }
}

此代码打印屏幕上的所有文件列表,但我的文件"lista plików"只有一个文件名(应该有更多)。我应该怎么做?

根据 PrinterWriter 的文档,如果文件存在,它将被"截断为零大小"。每次调用 new PrintWriter 时,文件都会被截断。

若要修复它,请只调用一次 PrintWriter 构造函数,而不是每次要写入文件时。

这是因为您每次在 zapis() 调用中都会重写文件。你可以写一个包装器你的列表文件文件夹()并从外部程序调用它。在该例程中,您应该打开文件,调用 listFilesForFolder(),然后关闭该文件。

private static PrintWriter zapPW = null;
public static void listFilesForFolderWrapper(File folder) throws FileNotFoundException  {
  PrintWriter zapPW = new PrintWriter(fs2);
  listFilesForFolder(folder);
  zapPW.close();
}

你的 zapis() 应该像这样简单:

static void zapis(String plik)throws FileNotFoundException {
       zapPW.println(plik+ "rn");
}

我不一定会以这种方式编码(对所有事情都使用静态..)。

最新更新