我已经尝试使用BufferedReader
类找到以下Java代码,以读取文本流。
public void editTexts(Path inputFile) throws IOException{
BufferedReader reader = Files.newBufferedReader(inputFile)){
// ----------
}
}
就像在此代码中一样,参数类型被称为
Path
。我在传递参数时遇到了问题。我想知道如何将参数传递给
Path
参数类型? 最佳答案
假设您有一个Path
指向目录,例如Windows计算机的根目录。
您可以这样创建Path
:
Path rootPath = Paths.get("C:\\");
如果现在要传递诸如文件名之类的参数,则可以执行此操作
String fileName = "some_file.txt";
Path filePath = rootPath.resolve(fileName);
为确保一切正常,请打印两个
Path
的绝对路径System.out.println("root path is " + rootPath.toAbsolutePath().toString());
System.out.println("path to the file in root is " + fileInRootPath.toAbsolutePath().toString());
您可以对这些
Path
执行检查,因为在内存中创建它们并不一定意味着路径正确并且文件系统对象存在。// check if the path exists
if (Files.exists(filePath)) {
// check if the path points to a regular file (not a directory or symbolic link)
if (Files.isRegularFile(filePath)) {
System.out.println(filePath.toAbsolutePath().toString()
+ " exists and is a regular file");
} else {
System.out.println(filePath.toAbsolutePath().toString()
+ " exists, but is not a regular file");
}
} else {
System.out.println(filePath.toAbsolutePath().toString()
+ " does not exist");
}