Java 使用 FileReader 会导致编译器错误“未处理的异常类型 FileNotFoundException”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6488339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using FileReader causes a compiler error "unhandled exception type FileNotFoundException"
提问by jason
Ive read a few threads here that relate the same problem, but the solutions arent working. :/
我在这里阅读了一些与相同问题相关的线程,但解决方案不起作用。:/
I use Eclipse, here is my program.
我使用 Eclipse,这是我的程序。
package mypackage;
import java.io.*;
public class myclass {
public static void main(String[] args) {
//String myfile = "/home/jason/workspace/myproject/src/mypackage/myscript.abc";
String myfile = "src/mypackage/myscript.abc";
File file1 = new File(myfile);
if(file1.exists()) {
log(myfile + " exists. length : " + myfile.length());
}
else{
log(myfile + " does not exist");
//System.exit(1);
}
//FileReader fr = new FileReader("myscript.abc");//I uncomment this and die inside
System.out.println("\nAbsPath : " + new File(".").getAbsolutePath());
System.out.println("\nuser.dir : " + System.getProperty("user.dir"));
}
public static void log(String s){
System.out.println(s);
}
}
}
The error I get, no matter what I try, or where I put myscript.abc (its peppered throughout the projects directory now) is this :
我得到的错误,无论我尝试什么,或者我把 myscript.abc 放在哪里(它现在遍布整个项目目录)是这样的:
Unhandled exception type FileNotFoundException myclass.java /myproject/src/mypackage
未处理的异常类型 FileNotFoundException myclass.java /myproject/src/mypackage
Wits end, pulling hairs.
斗智斗勇,拔毛。
回答by Perception
Use the file descriptor that you created and verified before creating the file reader. Also, you will probably run into problems using relative paths. Why is the line with the full path commented out? In any case, here is the code:
使用您在创建文件读取器之前创建和验证的文件描述符。此外,您可能会遇到使用相对路径的问题。为什么注释掉完整路径的那一行?无论如何,这是代码:
if(file1.exists()) {
log(myfile + " exists. length : " + myfile.length());
FileReader fr = new FileReader(file1);
}
回答by Edwin Buck
You are expecting Eclipse to run the program in the project root directory. Unless you did something special with your "Run" configuration, I'd be suprised if it really starts there.
您希望 Eclipse 运行项目根目录中的程序。除非你对“运行”配置做了一些特别的事情,否则我会很惊讶它真的从那里开始。
Try printing out your current working directory to make sure this is the right path.
尝试打印出您当前的工作目录以确保这是正确的路径。
Then try verifying that the bin / build directory contains your "*.abc" files, as they are not Java source files and may have not been copied into the compilation output directory.
然后尝试验证 bin / build 目录是否包含您的“*.abc”文件,因为它们不是 Java 源文件并且可能尚未复制到编译输出目录中。
Assuming that they are in the compliation directory, rewrite your file loader to use a relative path based on the class laoder's path. This will work well in exanded collections of .class files in directories (and later in packed JAR files).
假设它们在 compliation 目录中,重写您的文件加载器以使用基于类 laoder 路径的相对路径。这将适用于目录中 .class 文件的扩展集合(以及稍后在打包的 JAR 文件中)。
回答by Bohemian
Instead of trying to figure out what's going on, why not printwhat's going on...
与其试图弄清楚发生了什么,为什么不打印发生了什么......
Make this change to your code:
对您的代码进行此更改:
log(myfile.getName() + "(full path=" + myfile.getAbsolutePath() + ") does not exist");
You might find it either isn't using the directory you think, or (depending on your filesystem) it might be trying to create a file whose name is literally "src/mypackage/myscript.abc"
- ie a filename with embedded slashes.
您可能会发现它没有使用您认为的目录,或者(取决于您的文件系统)它可能试图创建一个名称为字面意思"src/mypackage/myscript.abc"
的文件 - 即带有嵌入斜杠的文件名。
回答by Tim Bender
Unhandled exception type FileNotFoundException myclass.java /myproject/src/mypackage
未处理的异常类型 FileNotFoundException myclass.java /myproject/src/mypackage
This is a compiler error. Eclipse is telling you that your program does not compile to java byte code (so of course you can't run it). For now, you can fix it by simply declaring that your program may throw this exception. Like so:
这是一个编译器错误。Eclipse 告诉你你的程序没有编译成 java 字节码(所以你当然不能运行它)。现在,您可以通过简单地声明您的程序可能抛出此异常来修复它。像这样:
public static void main(String[] args) throws FileNotFoundException {
FileNotFoundException
is a "checked exception" (google this) which means that the code has to state what the JVM should do if it is encountered. In code, a try-catch block or a throws declaration indicate to the JVM how to handle the exception.
FileNotFoundException
是一个“检查异常”(谷歌这个),这意味着代码必须说明如果遇到 JVM 应该做什么。在代码中,try-catch 块或 throws 声明向 JVM 指示如何处理异常。
For future reference, please note that the red squiggly underline in Eclipse means there is a compiler error. If you hover the mouse over the problem, Eclipse will usually suggest some very good solutions. In this case, one suggestion would be to "add a throws clause to main".
为了将来参考,请注意 Eclipse 中的红色波浪下划线表示存在编译器错误。如果您将鼠标悬停在问题上,Eclipse 通常会建议一些非常好的解决方案。在这种情况下,一个建议是“向 main 添加一个 throws 子句”。
回答by MockerTim
I see that you tried to specify the full path to your file, but failed because of the following mistake:
我看到您尝试指定文件的完整路径,但由于以下错误而失败:
you haven't declared or tried to catchjava.io.FileNotFoundException
.
你还没有声明或试图抓住java.io.FileNotFoundException
.
To fix it, you can replace the line
要修复它,您可以更换线
FileReader fr = new FileReader("myscript.abc");
with the code:
使用代码:
try {
FileReader fr =
new FileReader("/home/jason/workspace/myproject/src/mypackage/myscript.abc");
} catch (FileNotFoundException ex) {
Logger.getLogger(myclass.class.getName()).log(Level.SEVERE, null, ex);
}
The following code is successfully compiled, and it should work:
以下代码已成功编译,它应该可以工作:
package mypackage;
import java.io.*;
// It's better to use Camel style name for class name, for example: MyClass.
// In such a way it'll be easier to distinguish class name from variable name.
// This is common practice in Java.
public class myclass {
public static void main(String[] args) {
String myfile =
"/home/jason/workspace/myproject/src/mypackage/myscript.abc";
File file1 = new File(myfile);
if (file1.exists()) {
log("File " + myfile + " exists. length : " + myfile.length());
} else {
log("File " + myfile + " does not exist!");
}
try {
FileReader fr = new FileReader(myfile);
} catch (FileNotFoundException ex) {
// Do something with mistake or ignore
ex.printStackTrace();
}
log("\nAbsPath : " + new File(".").getAbsolutePath());
log("\nuser.dir : " + System.getProperty("user.dir"));
}
public static void log(String s) {
System.out.println(s);
}
}
回答by harun ugur
you can fix it simply declaring that throw this exception. Like this:
你可以简单地声明抛出这个异常来修复它。像这样:
public static void main(String args[]) throws FileNotFoundException{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
}