I am making a game with a world save/load function, which requires me to read/write to a text file. My problem is accesing it, I can read and write to it fine while in the editor, but when the project is compiled into a standalone jar it cannot find the file. Working on the site as an web applet isn't an issue. This is my read/write code:
import java.io.*; public class ReadWrite { static public String getContents(File aFile) { //...checks on aFile are elided StringBuilder contents = new StringBuilder(); try { //use buffering, reading one line at a time //FileReader always assumes default encoding is OK! BufferedReader input = new BufferedReader(new FileReader(aFile)); try { String line = null; //not declared within while loop /* * readLine is a bit quirky : * it returns the content of a line MINUS the newline. * it returns null only for the END of the stream. * it returns an empty String if two newlines appear in a row. */ while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty("line.separator")); } } finally { input.close(); } } catch (IOException ex){ ex.printStackTrace(); } return contents.toString(); } static public void setContents(File aFile, String aContents) throws FileNotFoundException, IOException { if (aFile == null) { throw new IllegalArgumentException("File should not be null."); } if (!aFile.exists()) { throw new FileNotFoundException ("File does not exist: " + aFile); } if (!aFile.isFile()) { throw new IllegalArgumentException("Should not be a directory: " + aFile); } if (!aFile.canWrite()) { throw new IllegalArgumentException("File cannot be written: " + aFile); } //use buffering Writer output = new BufferedWriter(new FileWriter(aFile)); try { //FileWriter always assumes default encoding is OK! output.write( aContents ); } finally { output.close(); } } public static void write(String fileName,String contents) { try { File file =new File(fileName+".txt"); setContents(file,contents); System.out.println(file.getPath()); } catch(java.io.FileNotFoundException r){ System.err.println("FontFormatException: " + r.getMessage()); } catch(java.io.IOException r){ System.err.println("FontFormatException: " + r.getMessage()); } } public static String read(String fileName) { return getContents(new File(fileName+".txt")); } }