[英]FileNotFoundException but File present at right path
I'm new to programming, every time I try to read a file.每次我尝试读取文件时,我都是编程新手。 I get FileNOtFoundException.我得到 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?有没有其他方法可以读取文件?
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您必须使用名称filename
定义文件的完整路径,否则它将打开不在当前工作目录的文件,您应该尝试
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: Java, reading a file from current directory?您可以在以下位置阅读更多内容: Java,从当前目录读取文件?
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此外,您正在关闭try
内的FileReader
,而不是关闭Scanner
,如果发生某些错误,这些资源将永远不会关闭,您需要将这些关闭语句放在finally
块中,或者更好地使用 try 与资源
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.