列出所有文件的程序有什么问题?

时间:2017-03-13 03:13:08

标签: java

我是初学者,想知道下面的代码有什么问题。 我运行了代码,但它只能列出C:\ JavaData

中某个子文件夹中的文件
import java.io.*;
import java.util.*;

class fileNames
{
    public static void main(String[] args) throws IOException
    {
        File dir = new File("C:\\JavaData");
        File desFile = new File(dir,"list.txt");
        writeFileNames(dir,desFile);
    }
    public static void writeFileNames(File dir,File desFile) throws IOException
    {
        BufferedWriter bfw = new BufferedWriter(new FileWriter(desFile));
        File[] files = dir.listFiles();


        for(File f : files)
        {
            if(f.isDirectory())
            {
                writeFileNames(f,desFile);
            }
            else
            {
                bfw.write(f.getAbsolutePath());
                bfw.newLine();
                bfw.flush();
            }

        }
        bfw.close();
    }
}

1 个答案:

答案 0 :(得分:0)

传递Writer(不是File desFile),你打开文件写入第一次调用(当你递归时,你仍然打开它)。另外,我使用的是try-with-resources而不是明确的close()。像,

public static void main(String[] args) throws IOException {
    File dir = new File("C:\\JavaData");
    File desFile = new File(dir, "list.txt");
    try (BufferedWriter bfw = new BufferedWriter(new FileWriter(desFile))) {
        writeFileNames(dir, bfw);
    }
}

public static void writeFileNames(File dir, BufferedWriter bfw) throws IOException {
    File[] files = dir.listFiles();
    for (File f : files) {
        if (f.isDirectory()) {
            writeFileNames(f, bfw);
        } else {
            bfw.write(f.getAbsolutePath());
            bfw.newLine();
            bfw.flush();
        }
    }
}