Edit1: Updated my method. I think it helped… I wont be able to be sure until I can test it later.
Edit2: Reverted back to previous version to show the change from the original to the answer.
This is part of a bigger problem I’m having trying to distribute my program to other computers. I have a method which reads a file (specifically an XML file, but I think that’s irrelevant) into a String. This is a GUI application so the user selects a file and that file is read by this method. I also use this method to read resources, which is why I have the catch for a FileNotFoundException. If that’s caught then it tries to read it as a resource instead. If that doesn’t work then too bad I guess… Haha.
So there are 4 different kinds of I’m trying on this:
- Work computer (development computer) in NetBeans (my IDE): works
- Work computer from the jar (compiled by NetBeans): works
- Personal computer in NetBeans (I’m using Dropbox so the files are synced up pretty well and all my references are correct): works
- Personal computer from the jar (compiled by NetBeans): DOES NOT WORK
As far as I can tell, what happens for that last case is for some reason fileScanner.hasNext() returns false on the first go of the loop so nothing is appended to the fileString. I just don’t know what would cause it to behave this way! Any help would be appreciated! (Note, there is no error thrown, it all “works” fine as far as the computer things).
Here are my methods. Any help improving it would be appreciated as well!
/**
* This method reads a file into a string. If you have an file in the resources folder for example, you can say
* "/resources/exampleFile.txt".
*
* @param location location of the resource in the resources folder
* @return String of the file
*/
public static String fileToString(String location) throws FileNotFoundException {
Scanner fileScanner;
try {
InputStream is = StaticClass.class.getResourceAsStream(location);
fileScanner = new Scanner(is);
} catch (NullPointerException e) {
fileScanner = new Scanner(new File(location));
}
StringBuilder fileString = new StringBuilder();
while (fileScanner.hasNext()) {
fileString.append(fileScanner.nextLine()).append(newline);
}
return fileString.toString();
}
I’m still not sure why, but I think it had to do with the Scanner. For some reason it wasn’t working quite right, but I just changed it to the following code:
The biggest change was using FileReaders and StringWriters instead of Scanners. I also separated my resourceToString and fileToString methods. I think that’s better anyway. So, anyway, there you go! I hope this helps someone in the future!