views:

181

answers:

4

hello guys

I have a file on a jar file; it's 1.txt for example

how can I call it ; my source code is :

Double result=0.0;
        try {
              File file = new File("1.txt")); //how get this file from a jar file
              BufferedReader input =
                new BufferedReader(new FileReader(file));
              String line;
              while ((line = input.readLine()) != null) {
                 if(me==Integer.parseInt(line.split(":")[0])){
                     result= parseDouble(line.split(":")[1]);
                 }
              }
              input.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        return result;

thanks ...

+2  A: 

You can't use File, since this file does not exist independently on the file system. Instead you need getResourceAsStream(), like so:

...
InputStream in = getClass().getResourceAsStream("/1.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(in));
...
Sean Owen
Assuming the calling class is inside the jar file of course. Otherwise he can just unzip it a read it using the classes in `java.util.jar` (or even more basic, as a plain old zip file using `java.util.zip`).
Martin Wickman
Thanks Dear Sean ...
Mike Redford
+1  A: 

Something similar to this answer is what you need.

You need to pull the file out of the archive in that special way.

BufferedReader input = new BufferedReader(new InputStreamReader(
         this.getClass().getClassLoader().getResourceAsStream("1.txt")));
jjnguy
BufferedReader doesn't except `InputStream` argument
Bozho
@Bozho Thanks, slight oversight on my part.
jjnguy
+5  A: 

If your jar is on the classpath:

InputStream is = YourClass.class.getResourceAsStream("1.txt");

If it is not on the classpath, then you can access it via:

URL url = new URL("jar:file:/absolute/location/of/yourJar.jar!/1.txt");
InputStream is = url.openStream();
Bozho
A: 

A Jar file is a zip file.....

So to read a jar file, try

ZipFile file = new ZipFile("whatever.jar");
if (file != null) {
   ZipEntries entries = file.entries(); //get entries from the zip file...

   if (entries != null) {
      while (entries.hasMoreElements()) {
          ZipEntry entry = entries.nextElement();

          //use the entry to see if it's the file '1.txt'
          //Read from the byte using file.getInputStream(entry)
      }
    }
}

//Hope this helps.

The Elite Gentleman
The other answers are correct, I just gave another alternative.
The Elite Gentleman