File not found?

大城市里の小女人 提交于 2020-01-06 14:21:56

问题


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!

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?

This is my code:

private static final String fileF = "File.txt";
private static final ArrayList<String[]> instructionsF =
CreatureReader.readInstructions(fileF);

回答1:


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.




回答2:


Two things to notice:

  1. check if "File.txt" is really named like that, since it won't find "file.txt" -> case sensitivity matters!
  2. 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

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.




回答3:


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.



来源:https://stackoverflow.com/questions/4340048/file-not-found

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!