0

I was having some issues getting the executable jar file for my project to work (outside of the eclipse IDE). I figured out the issue with java -jar fileName.jar

Here's the code:

fileIn = new Scanner(new File("src//resources//TestSave.txt"));

Through a little troubleshooting and research I understand that this wasn't working in the executable jar because it doesn't have a src folder, that's only created within the IDE. Here was my solution:

fileIn = new Scanner(new File("D://resources//TestSave.txt"));

The only problem with this is that if I want to put this program on my resume then who ever views it will have to place the folder into their D drive. I want it to be quick and easy so that they can just view my project with no hassle.

How can I access the resources folder within the executable jar file itself without having to reference/create any outside folders?

jaycalli
  • 9
  • 2
  • Use classloader.getResources() see here http://stackoverflow.com/questions/1429172/how-do-i-list-the-files-inside-a-jar-file – Guenther Sep 15 '16 at 18:08
  • Possible duplicate of [Reading a resource file from within jar](http://stackoverflow.com/questions/20389255/reading-a-resource-file-from-within-jar) – VGR Sep 15 '16 at 18:34
  • Look at my answer to [this question](http://stackoverflow.com/questions/38483934/cannot-read-a-property-file-in-java-6-in-a-runnable-jar/38485873#38485873); it might help you; read my comments to the answer too. – ujulu Sep 15 '16 at 18:39

2 Answers2

0

You have two options.

  1. put the file in the same file as executable jar fileIn = new Scanner(new File("./TestSave.txt"));

  2. Follow this post reading-a-resource-file-from-within-jar

Community
  • 1
  • 1
r00tt
  • 257
  • 3
  • 18
  • I am unfamiliar with InputStreams and BufferReader, am I to assume that they work the same way as File type class and Scanner type respectively? – jaycalli Sep 15 '16 at 19:55
  • @jaycalli it is really depends on what you want to do with the content. If you want to read the entire file you can use something like this [/how-to-convert-inputstream-to-string-in-java](https://www.mkyong.com/java/how-to-convert-inputstream-to-string-in-java/). My recommendation is to spend some time to understand concepts of InputStream and BufferReader if you plan to use something related to that on your resume. – r00tt Sep 15 '16 at 21:25
0

Use getResourceAsStream (no File) within a JAR:

InputStream inputStream = classLoader.getResourceAsStream("TestSave.txt");
Scanner input = new Scanner(inputStream);
Hermann Schwarz
  • 1,495
  • 1
  • 15
  • 30