标题翻译
FileNotFoundException but File present at right path
问题
我是编程新手,每次尝试读取文件时都会收到FileNOtFoundException错误。
我可能出了什么问题?
```java
import java.io.*;
import java.util.Scanner;
public class ReadFile
{
public ReadFile()
{
readFile();
}
public void readFile()
{
String filename = "trees.txt";
System.out.println(new File(".").getAbsolutePath()); //文件在这个路径上。
String name = "";
try
{
FileReader inputFile = new FileReader(filename);
Scanner parser = new Scanner(inputFile);
while (parser.hasNextLine())
{
name = parser.nextLine();
System.out.println(name);
}
inputFile.close();
}
catch (FileNotFoundException exception)
{
System.out.println(filename + " not found");
}
}
}
是否有其他方法可以读取文件?
<details>
<summary>英文翻译</summary>
I'm new to programming, every time I try to read a file. I get FileNOtFoundException.
Where could I be going wrong?
import java.io.*;
import java.util.Scanner;
public class ReadFile
{
public ReadFile()
{
readFile();
}
public void readFile()
{
String filename = "trees.txt";
System.out.println(new File(".").getAbsolutePath()); //file is at this path.
String name = "";
try
{
FileReader inputFile = new FileReader(filename);
Scanner parser = new Scanner(inputFile);
while (parser.hasNextLine())
{
name = parser.nextLine();
System.out.println(name);
}
inputFile.close();
}
catch (FileNotFoundException exception)
{
System.out.println(filename + " not found");
}
}
}
Is there any other way I could read the file?
</details>
# 答案1
**得分**: 0
这段代码
```java
FileReader inputFile = new FileReader(filename);
如果没有定义完整的文件路径和名称 filename,它会打开文件,但不会在当前工作目录中打开。
你应该尝试
FileReader inputFile = new FileReader(new File(new File("."), filename));
// 定义 new File("."),意味着你将在当前工作目录中打开文件
你可以在这里阅读更多:https://stackoverflow.com/questions/1480398/java-reading-a-file-from-current-directory
英文翻译
this code
FileReader inputFile = new FileReader(filename);
You must define full path to file with name filename if not it will open file not at current working directory
you should try
FileReader inputFile = new FileReader(new File(new File("."), filename));
// defind new File(".") it mean you will you open file in current working directory
you can read more at: https://stackoverflow.com/questions/1480398/java-reading-a-file-from-current-directory
答案2
得分: 0
尝试打印实际尝试打开的文件路径,以确保文件存在于正确的位置。
String filename = "trees.txt";
File file = new File(filename);
System.out.println(file.getAbsolutePath());
另外,你在 try 内部关闭了 FileReader,但没有关闭 Scanner,如果出现错误,这些资源将永远不会被关闭,你需要将这些关闭语句放在一个 finally 块中,或者更好地使用带资源的 try。
英文翻译
Try printing the path of the file you are actually trying to open so you can be sure that the file exists in the right location
String filename = "trees.txt";
File file = new File(filename);
System.out.println(file.getAbsolutePath());
Also, you are closing the FileReader inside the try, and not closing the Scanner, if some error ever occurs those resources will never be closed, you need to put those close statements in a finally block, or better use try with resources
专注分享java语言的经验与见解,让所有开发者获益!

评论