• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading from a file from inside a jar

 
John Forsyth
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • 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.
 
kamal kannan
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • 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);
}
}
}
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • 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?
 
Rob Spoor
Sheriff
Posts: 20822
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!