【发布时间】:2020-03-22 11:15:56
【问题描述】:
我写了一个小工具,将给定目录下的所有目录和文件名打印到文件中。程序编译得很好,但是运行程序后,文件没有被写入。这在我看来很奇怪。程序代码如下所示。
在代码的第 49 行,当我只使用文件作为方法的参数时,没有问题,并且写入了输出文件。请尝试并查看结果。但是当我使用 file.getFileName() 作为参数时,输出文件根本没有写入!
非常感谢您的帮助。
/**
* This program walks a directory tree
* and prints out the directory name and the file names under it.
* @author Michael Mei
* @version 1.0 22-03-2020
*/
package walkDirectory;
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import static java.nio.file.FileVisitResult.*;
import static java.nio.file.FileVisitOption.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class DirWalkerPrinter extends SimpleFileVisitor<Path> {
private Path outPath;
private Writer out;
private int fileCount;
private int dirCount;
DirWalkerPrinter (Path outPath) throws IOException {
this.outPath = outPath;
out = Files.newBufferedWriter(outPath, StandardCharsets.UTF_16, StandardOpenOption.WRITE);
}
public int getFileCount () {
return fileCount;
}
public int getDirCount () {
return dirCount;
}
public void writeResults(Path p) throws IOException {
// Using System.out.println(p.toString()) was also working.
out.write(p.toString());
out.write("\n");
}
public void done () throws IOException {
out.write(fileCount + " of files found in " + dirCount);
}
@Override
public FileVisitResult visitFile (Path file, BasicFileAttributes attrs) throws IOException {
writeResults(file.getFileName()); // line 49
fileCount++;
return CONTINUE;
}
public FileVisitResult postVisitDirectory (Path dir, BasicFileAttributes attrs) throws IOException {
writeResults(dir);
dirCount++;
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed (Path file, IOException e) {
System.err.println(e);
return CONTINUE;
}
public static void main(String[] args) throws IOException {
if (args.length < 2) {
System.err.println("java DirWalkerPrinter source-path destination-file");
System.exit(-1);
}
Path startingDir = Paths.get(args[0]);
Path writeToDir = Paths.get(args[1]);
DirWalkerPrinter dirWalkerPrinter = new DirWalkerPrinter(writeToDir);
Files.walkFileTree(startingDir, dirWalkerPrinter);
dirWalkerPrinter.done();
int fileCount = dirWalkerPrinter.getFileCount();
int dirCount = dirWalkerPrinter.getDirCount();
System.out.println(fileCount + " of files found in " + dirCount);
}
}
【问题讨论】:
-
嗯,看起来解决方案是使用
file作为参数,而不是file.getFIleName()。如果 'file` 已经在工作,是什么让您认为使用file.getFIleName()会有所改进? -
你关闭过BufferedWriter吗?
-
@KevinAnderson谢谢你的评论,凯文。我使用 file.getFileName() 因为当写入文件时,同一目录下的文件名看起来几乎相同,将文件名正确保存在整个文件名字符串的末尾。那会使结果难看。所以,我打算把同一目录下文件名的相同部分删掉。这会让事情看起来很整洁。
-
@NomadMaker谢谢你,NomadMaker。我忘了关闭 BufferedWriter。现在我关闭了它。