Reading a text file from a .jar file

I have a rookie question.

I am currently writing a program that extracts a lot 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 extracts the data from the text file correctly in the IDE, but when I run the program as a .jar file, the file cannot be restored.

I got a little familiar with adding a text file to a .jar file and using the InputStream and BufferedReader classes to read the file, but I never used these classes and don’t understand what they do differently / how to use them instead of the File and Scanner classes.

Can anyone help me out?

+4
source share
2 answers

The Scanner class has a Scanner(InputStream) constructor Scanner(InputStream) ; therefore, you can still use this class to read data, as you did before.

All you have to do is read the file from the Jar, you can do it like this:

 InputStream is = getClass().getResourceAsStream("champdata.txt"); Scanner read = new Scanner(is); read.useDelimiter("%"); 

If a file called champdata.txt is located at the root of your jar file (which is just a zip file, you can use any unzipper to check where the file is located).

Now, if you want to have the same functionality when developing in your IDE, put the file in your source directory so that when the project is built, it will be placed in your classes folder. Thus, the file can be loaded as described above using getResourceAsStream()

+2
source

You will need to get the file at the URL, because it is an embedded resource. See the built-in Wiki for more information .

Update

So, if I placed the text file in the Resource folder in the src folder, then the URL I used would be "resources / champdata.txt"

No. If it is in the Resource path in the Jar, the line should be:

 ..getResource("/Resource/champdata.txt"); 

If it is in the resources path:

 ..getResource("/resources/champdata.txt"); 

The string must be an exact letter, ( plural &) case.

+3
source

Source: https://habr.com/ru/post/1440619/


All Articles