gpt4 book ai didi

Java文件I/O问题: file now written by newBufferedWriter

转载 作者:行者123 更新时间:2023-12-02 08:50:42 28 4
gpt4 key购买 nike

我写了一个小工具,用于将给定目录下的所有目录和文件名打印到文件中。程序编译正常,但运行程序后,文件未写入。这对我来说看起来很奇怪。程序代码如下所示。

在代码的第49行,当我仅使用file作为方法的参数时,没有问题并且输出文件被写入。请尝试一下并查看结果。但是当我使用 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.getFileName()

此函数将仅返回文件名 - 没有完整路径。您的代码将尝试在您执行的同一目录中创建该文件。 (因为你只输入文件名)

这可能是您的问题。

关于Java文件I/O问题: file now written by newBufferedWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60798620/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com