by running this...
File file = new File(\"Highscores.scr\");
i keep getting this error, and i really don\'t know how to get around it. the fil
The best way to do this is to put it in your classpath then getResource()
package com.sandbox;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
public class Sandbox {
public static void main(String[] args) throws URISyntaxException, IOException {
new Sandbox().run();
}
private void run() throws URISyntaxException, IOException {
URL resource = Sandbox.class.getResource("/my.txt");
File file = new File(resource.toURI());
String s = FileUtils.readFileToString(file);
System.out.println(s);
}
}
I'm doing this because I'm assuming you need a File
. But if you have an api which takes an InputStream
instead, it's probably better to use getResourceAsStream
instead.
Notice the path, /my.txt
. That means, "get a file named my.txt that is in the root directory of the classpath". I'm sure you can read more about getResource
and getResourceAsStream
to learn more about how to do this. But the key thing here is that the classpath for the file will be the same for any computer you give the executable to (as long as you don't move the file around in your classpath).
BTW, if you get a null pointer exception on the line that does new File
, that means that you haven't specified the correct classpath for the file.