Java - 文件 IO - AbsolutePath() 不 return 文件路径
Java - File IO - AbsolutePath() does not return the path to the file
在过去的几天里,我一直在努力让这个方法起作用,但总是遇到同样的问题。除非指定文件路径并设置格式,否则我的文件将无法打开。
这是我的代码:
text = new MyArrayList<>();
String filePath = new File(fileName).getAbsolutePath();
filePath = filePath.replace('\', '/');
try {
Scanner s = new Scanner(new File(filePath));
while (s.hasNext()) {
text.add(s.next());
}
s.close();
}
catch(FileNotFoundException e){
System.out.println("File not found.");
}
出于某种原因,当我调用 getAbsolutePath() 时,它给了我这个路径:“C:/Zaid/College/CE2336/Programs/File.txt”
而实际上允许我访问该文件的文件路径是:
"C:/Zaid/College/CE2336/Programs/MyImplementations/File.txt"
我不明白我应该做什么来清理它。
P.S。 MyImplementations 是文本文件和我的代码所在的包。
当你打电话时
String filePath = new File(fileName).getAbsolutePath();
您正在项目的根目录中创建文件,然后获取该路径而不是您已经拥有并想要获取的文件
这对你的情况应该足够了:
Scanner s = new Scanner(new File(fileName));
还要确保在处理错误时共享您拥有的所有信息:打印未找到的文件。您会发现这使得故障排除变得非常容易。
catch(FileNotFoundException e){
System.out.println("File not found.");
e.printStackTrace(System.out);
}
在过去的几天里,我一直在努力让这个方法起作用,但总是遇到同样的问题。除非指定文件路径并设置格式,否则我的文件将无法打开。
这是我的代码:
text = new MyArrayList<>();
String filePath = new File(fileName).getAbsolutePath();
filePath = filePath.replace('\', '/');
try {
Scanner s = new Scanner(new File(filePath));
while (s.hasNext()) {
text.add(s.next());
}
s.close();
}
catch(FileNotFoundException e){
System.out.println("File not found.");
}
出于某种原因,当我调用 getAbsolutePath() 时,它给了我这个路径:“C:/Zaid/College/CE2336/Programs/File.txt”
而实际上允许我访问该文件的文件路径是: "C:/Zaid/College/CE2336/Programs/MyImplementations/File.txt"
我不明白我应该做什么来清理它。
P.S。 MyImplementations 是文本文件和我的代码所在的包。
当你打电话时
String filePath = new File(fileName).getAbsolutePath();
您正在项目的根目录中创建文件,然后获取该路径而不是您已经拥有并想要获取的文件
这对你的情况应该足够了:
Scanner s = new Scanner(new File(fileName));
还要确保在处理错误时共享您拥有的所有信息:打印未找到的文件。您会发现这使得故障排除变得非常容易。
catch(FileNotFoundException e){
System.out.println("File not found.");
e.printStackTrace(System.out);
}