Issue
Im working on a Minesweeper clone and I want the user to be able to save their fastest solve times to a .txt file. I have it set up and working inside Eclipse with the following code in my i/o class:
public static final String RECORD_FILE_NAME = "records/records.txt";
public static String readRecords() {
String records = "";
try {
Scanner scan = new Scanner(new FileInputStream(RECORD_FILE_NAME));
while (scan.hasNextLine()) {
records = records + scan.nextLine() + "\n";
}
scan.close();
} catch (Exception e) {
throw new IllegalArgumentException("Invalid file");
}
return records;
}
public static void writeRecords(String records, String fileName) {
try {
PrintStream writer = new PrintStream(new File(fileName));
writer.print(records);
} catch (Exception e) {
throw new IllegalArgumentException("Unable to save file.");
}
}
However, after exporting the project as a Runnable JAR File, the readRecords() method throws the IllegalArgumentException from inside the catch block. So, how should I set up file i/o so that it works outside of Eclipse? Any help is greatly appreciated, thanks!
Solution
A couple things to mention here:
If you want to open files safely, use a try-with-resources block
try (PrintStream writer = new PrintStream(new File(fileName))) {
writer.print(records);
}
The way you're currently doing it may not close the file since the writer is never closed, especially if an error is thrown upon catching an exception
Second, I don't think throwing an IllegalArgumentException is optimal here since you're essentially just hiding what the may be and instead of a helpful stacktrace you get just "Unable to save file.". This is epecially problematic if something other than an IO exception is thrown, as it will just hide it (e.g. if one of those methods isn't null-safe and somehow a nullpointerexception gets thrown)
To answer your question, records/records.txt is a relative file location, and may change
You'd best either go with a resource path file (extra examples) or a common file (a little less nice since it's platform-dependent), or the common locations method mentioned by MadProgrammer
Answered By - Jam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.