0

I am trying to use a jar file which itself is a web application in another web project. In my jar which i have created using eclipse's export to jar functionality, I have stored a directory.To access the files the from that directory i am using

BufferdReader tempDir = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(myDirPath),"UTF-8"));

// Then i iterate on tempDir

String line;
ArrayList<File> tempDirList = new ArrayList<File>(); 
int c = 0;
try {
    while((line = tempDir.readLine())!= null)
    {
       File f = new File(line);
       tempDirList.add(f);
           c++;
        }
     } catch (IOException e) 
    {
    e.printStackTrace();
    } 

Now on itrating on tempDirList when i try to read the file i need file path from which i get file but I did not get file path. So i want to know that how i get file path?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
prachi
  • 37
  • 1
  • 3
  • 9

1 Answers1

0

You cannot access the files in the JAR as File objects since in the web container they might not get unpacked (so there is no file). You can only access them via streams as you did.

getClass().getResourceAsStream(myDirPath + "/file1.txt"); 

If you really need File objects (most of the times it's quite easy to avoid that), copy the files into temporary files which you then can access.

File tmp = File.createTemp("prefix", ".tmp");
tmp.deleteOnExit();
InputStream is = getClass().getResourceAsStream(myDirPath + "/file1.txt");
OutputStream os = new FileOutputStream(tmp);
ByteStreams.copy(is, os);
os.close();
is.close();

But as I said, using streams instead of file objects in the first place makes you more flexible.

If you really don't know all the files in the directory at compile time you might be interested in this answer to list contents.

Community
  • 1
  • 1
Stephan
  • 7,360
  • 37
  • 46
  • I tried what u suggested but i get null value from following statement InputStream is = getClass().getResourceAsStream(myDirPath + fileName); is contains null – prachi Jan 31 '13 at 09:10
  • `myDirPath` and `fileName` contain `/` to separate them from each other? Does `myDirPath` start with a `/` or is the directory within the package of the current class? Have a look for clarification on how to read from a JAR at [this answer](http://stackoverflow.com/questions/1464291/how-to-really-read-text-file-from-classpath-in-java). – Stephan Jan 31 '13 at 09:26
  • Thanks Stephan, i can get the value in InputStream . Now the only problem is this "my file is a .owl file and i want to generate the model using that file so i want file path" so i need to write the statment like: Model timeModel = FileManager.get().loadModel(filePath, ApplicationConstants.N3); the filePath is actual path with file name for that i want filepath and problem is how to get it? – prachi Jan 31 '13 at 10:16