我正在尝试获取文件路径,以确保它是相同的,我什至使用了一个函数来返回文件的路径,即使文件路径是正确的,它也永远无法正常工作,我已经尝试过删除.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
答案 0 :(得分:1)
如果这是预期的路径
C:\Users\Dias\eclipse-workspace\pds\text.txt
然后肯定是文件不存在的解释。
如果这不是预期的路径,则说明您需要:
将路径正确编码到您的程序中,或
更改当前工作目录
'toAbsolutePath'不会四处查找文件,因此它知道绝对路径;而是看到您指定的路径是相对的,并在当前工作目录下添加前缀。