Read file – Java io. FileNotFoundException
•
Java
public void loadFile(int level){
public void loadFile(int level){ try { //Create new file levelFile = new File("assets/levels.txt"); fis = new FileInputStream(levelFile); isr = new InputStreamReader(fis); reader = new BufferedReader(isr); //Code to read the file goes here
However, with this code, I keep receiving the above error (Java. Io. FileNotFoundException)
The file must exist in my assets folder and have the correct name I found several similar problems here and tried all kinds of things, including refreshing the project, cleaning up the project, and using "levels. TXT" instead of "assets / levels. TXT", but I always received this error
Any ideas?
Solution
Because you are working outside the package, getresource () will be the best solution to your problem:
URL url = getClass().getResource("/assets/levels.txt"); File f = new File(url.toURI()); //....
Alternatively, you can use the getresourceasstream () method to get the input stream directly:
InputStream is= getClass().getResourceAsStream("/assets/levels.txt"); isr = new InputStreamReader(is);
It's better because you don't have to use FileInputStream
Note that urisyntaxexception must be captured or declared as thrown using FileNotFoundException
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码