我是初学者,想知道下面的代码有什么问题。 我运行了代码,但它只能列出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();
}
}
答案 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();
}
}
}