Java 文件未找到?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4340048/
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
File not found?
提问by Samuel
I have an assignment and we have a couple of classes given, one of them is a filereader class, which has a method to read files and it is called with a parameter (String) containing the file path, now i have a couple of .txt files and they're in the same folder as the .java files so i thought i could just pass along file.txt as filepath (like in php, relatively) but that always returns an file not found exception!
我有一个作业,我们有几个类,其中一个是文件读取器类,它有一个读取文件的方法,它用一个包含文件路径的参数(字符串)调用,现在我有几个 . txt 文件,它们与 .java 文件在同一个文件夹中,所以我想我可以将 file.txt 作为文件路径传递(就像在 php 中,相对)但是总是返回一个文件未找到异常!
Seen the fact that the given class should be working correctly and that i verified that the classes are really in the same folder workspace/src as the .java files i must be doing something wrong with the filepath String, but what?
看到给定的类应该正常工作的事实,并且我验证了这些类确实与 .java 文件在同一个文件夹工作区/src 中,我一定是文件路径字符串有问题,但是什么?
This is my code:
这是我的代码:
private static final String fileF = "File.txt";
private static final ArrayList<String[]> instructionsF =
CreatureReader.readInstructions(fileF);
采纳答案by Goran Jovic
Put this:
把这个:
File here = new File(".");
System.out.println(here.getAbsolutePath());
somewhere in your code. It will print out the current directory of your program.
在您的代码中的某处。它将打印出程序的当前目录。
Then, simply put the file there, or change the filepath.
然后,只需将文件放在那里,或更改文件路径。
回答by darioo
Two things to notice:
有两点需要注意:
- check if "File.txt" is really named like that, since it won't find "file.txt" -> case sensitivity matters!
- your file won't be found if you use relative filenames (without entire directory) and it isn't on your classpath -> try to put it where your
.class
files are generated
- 检查“File.txt”是否真的是这样命名的,因为它找不到“file.txt”->区分大小写很重要!
- 如果您使用相对文件名(没有整个目录)并且它不在您的类路径中,则不会找到您的
.class
文件-> 尝试将其放在生成文件的位置
So: if you've got a file named /home/javatest/File.txt
, you have your source code in /home/javatest/
and your .class
files in that same directory, your code should work fine.
所以:如果你有一个名为 的文件/home/javatest/File.txt
,你的源代码/home/javatest/
和.class
文件都在同一个目录中,你的代码应该可以正常工作。
回答by Jacob Tomaw
If you class is in package and you have placed the files as siblings then your path must include the package path. As suggested in other answers, print out the path of the working directory to determine where Java is looking for the file relative from.
如果您的类在包中并且您已将文件作为兄弟文件放置,则您的路径必须包含包路径。正如其他答案中所建议的那样,打印出工作目录的路径以确定 Java 正在寻找相对文件的位置。