I have a rookie question.
I'm currently writing a program that takes in alot of data from a text file using the File and Scanner class as shown below:
File data = new File("champdata.txt");
Scanner read = new Scanner(data);
read.useDelimiter("%");
The Scanner then retrieves data from the text file correctly while in the IDE, but when I run the program as a .jar file, the file cannot be retrieved.
I've read a little about adding a text file to the .jar file itself, and using the InputStream and BufferedReader classes to read the file, but I have never used these classes, nor do I understand what they do differently/how to use them in place of the File and Scanner classes.
Can anyone help me out?
The Scanner
class has a constructor Scanner(InputStream)
; so you can still use this class to read the data like you did before.
All you have to do is to read the file from the Jar, you can do this like so:
InputStream is = getClass().getResourceAsStream("champdata.txt");
Scanner read = new Scanner(is);
read.useDelimiter("%");
Where the file named champdata.txt
is located at the root of your jar file (which is just a zip file, you can use any unzipper to verify where the file is being located).
Now if you want to have the same functionality while developing in your IDE, place the file in your source directory, so that when the project is being built, it is placed in your classes
folder. This way, the file can be loaded as described above using getResourceAsStream()