• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Reading from a file from inside a jar

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am in need of a way for my program, which is inside a jar, to access a text file outside of the jar. The text file will always reside in the same place as my jar.
 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi you can read the file inside jar file the following code will help you
test.jar - is jar file
test.txt - is txt file inside test.jar

test.jar/test.file

the code as follows


import java.util.jar.*;
import java.io.*;
class test
{
public static void main(String []z)throws IOException
{
JarFile j=new JarFile("test.jar");
InputStream is=j.getInputStream(j.getEntry("test.txt"));
int i;
while((i=is.read())!=-1)
{
System.out.print((char)i);
}
}
}
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The question is about reading a file outside a jar, so this suggestion will not help.

Why can't you use regular file I/O?
 
Sheriff
Posts: 22815
132
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Ulf Dittmer:
Why can't you use regular file I/O?


I think the problem is that the location of both the JAR file and the text file can change, but they are always located in the same folder. Basically, the JAR location (and therefore the text location) needs to be determined at runtime.

Check out this article at Javaworld; it lists some code that can determine the physical location of a class.
 
Do not meddle in the affairs of dragons - for you are crunchy and good with ketchup. Crunchy tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic