java - 即使路径正确也无法获取路径
问题描述
我正在尝试获取我的文件路径,以确保它是相同的我什至使用了一个函数来返回文件的路径,即使文件的路径是正确的,它永远不会起作用,我试图删除.txt,只有文件名(因为它与此类在同一个包中)但似乎没有任何效果。
这是代码:
StringBuilder contentBuilder = new StringBuilder();
try
{
String filetest="text.txt";
Path pathToFile = Paths.get(filetest);
String name = pathToFile.toAbsolutePath().toString();
System.out.println("Path name: " + name);
Stream<String> stream = Files.lines( Paths.get(name), StandardCharsets.UTF_8);
stream.forEach(s -> contentBuilder.append(s).append("\n"));
String filename = contentBuilder.toString();
System.out.println(filename);
}
catch (IOException e)
{
e.printStackTrace();
System.out.println("Error: " + e);
}
输出
Path name: C:\Users\Dias\eclipse-workspace\pds\text.txt
java.nio.file.NoSuchFileException: C:\Users\Dias\eclipse-workspace\pds\text.txt
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:230)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.newByteChannel(Files.java:407)
at java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:384)
at java.nio.file.Files.newInputStream(Files.java:152)
at java.nio.file.Files.newBufferedReader(Files.java:2784)
at java.nio.file.Files.lines(Files.java:3744)
at lab7.Client.main(Client.java:23)
Error: java.nio.file.NoSuchFileException: C:\Users\Dias\eclipse-workspace\pds\text.txt
解决方案
如果这是预期的路径
C:\Users\Dias\eclipse-workspace\pds\text.txt
那么解释肯定是该文件不存在。
如果这不是预期的路径,那么解释是您需要:
将路径正确编码到您的程序中,或者
更改当前工作目录
'toAbsolutePath' 不会四处寻找文件,因此它知道绝对路径;相反,它会看到您指定的路径是相对的,并在其前面加上当前工作目录。
推荐阅读
- swift - Swift 中带有 CollectionView 和 TableView 的 UIView
- c++ - 为什么 while(!file.eof()) 会陷入无限循环?C++
- python - 使用来自另一个文件的参数打开一个 python 文件
- vba - vba 脚本将代码从文本文件复制到 ThisoutlookSession 模块
- android - 在 React Native Camera 中使用 focusDepth 时图像失焦
- django - 在 Django 应用程序中使用 Heroku Connect 中的 Salesforce 自定义字段
- reactjs - React useContext 不会更新子组件,但适用于页面刷新
- forms - 在 null 上调用了方法“更新”
- xamarin.forms - Xamarin iOS 部署到应用商店导致“无效的捆绑结构 [...] GoogleMaps”错误
- python-3.x - Python 的 setter 概念在处理列表数据时不是很有用吗?