英文:
Recursive method doesn't work with FileWriter
问题
我有一个方法,应该将一个给定目录的结构以树状视图写入文件。但是它不会写入子文件夹及其文件,所以我尝试添加了递归调用,但出于某种原因它不起作用。我该如何修复?
public void readFiles() {
File baseDirectory = new File(path);
if (baseDirectory.isDirectory()) {
try (FileWriter writer = new FileWriter("D:/info.txt")) {
for (File file : baseDirectory.listFiles()) {
if (file.isFile()) {
writer.append(" |------ " + file.getName());
writer.append("\n");
} else if (file.isDirectory()) {
writer.append(" |+++++ " + file.getName());
writer.append("\n");
path = file.getPath().replace("\\", "/");
readFiles(); // 递归调用在此处
}
}
writer.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
主类:
public class Runner {
public static void main(String[] args) {
TreeViewer treeViewer = new TreeViewer();
treeViewer.setPath("D:/test");
treeViewer.readFiles();
}
}
英文:
I have a method that should write down in a file a structure of a given directory in a tree view. But it doesn't write down subfolders and their files, so I tried adding a recursive call, but for some reason it doesn't work. How can i fix it?
public void readFiles() {
File baseDirectory = new File(path);
if (baseDirectory.isDirectory()) {
try (FileWriter writer = new FileWriter("D:/info.txt")) {
for (File file : baseDirectory.listFiles()) {
if (file.isFile()) {
writer.append(" |------ " + file.getName());
writer.append("\n");
} else if (file.isDirectory()) {
writer.append(" |+++++ " + file.getName());
writer.append("\n");
path = file.getPath().replace("\\", "/");
readFiles(); // recursive call here
}
}
writer.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Main class :
public class Runner {
public static void main(String[] args) {
TreeViewer treeViewer = new TreeViewer();
treeViewer.setPath("D:/test");
treeViewer.readFiles();
}
}
[Example of the output file: ][1]
答案1
得分: 0
试试这个。
static void tree(File file, String indent, Writer out) throws IOException {
out.write(indent + file.getName() + System.lineSeparator());
if (file.isDirectory())
for (File child : file.listFiles())
tree(child, indent + " ", out);
}
public static void main(String[] args) throws IOException {
try (Writer out = new FileWriter("D:/info.txt")) {
tree(new File("D:/test"), "", out);
}
}
英文:
Try this.
static void tree(File file, String indent, Writer out) throws IOException {
out.write(indent + file.getName() + System.lineSeparator());
if (file.isDirectory())
for (File child : file.listFiles())
tree(child, indent + " ", out);
}
public static void main(String[] args) throws IOException {
try (Writer out = new FileWriter("D:/info.txt")) {
tree(new File("D:/test"), "", out);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论