2

I have a products.jar file. Inside that there is one class com.ClassA. The structure of the project is like

products
    |--test
        |--com
            |--ClassA.java
        |--dependencies
            |---inputs.txt

Inside eclipse, ClassA.java is accessing the inputs.txt file by the following path and it is working fine

private static final String PROPERTIES_FILE_PATH = "test/dependencies/inputs.txt";

test package is in the java build path -> sources

But when I am exporting this project as products.jar, I find that in the jar file there is no test directory. There are two dirs com and dependencies at the root of the jar file. So when I am trying to execute the ClassA (residing in jar file) through command line, I am getting the following exception:

JUnit version 4.8.2
java.io.FileNotFoundException: test/dependencies/inputs.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:137)
at java.io.FileInputStream.<init>(FileInputStream.java:96)

So after finding that test dir is not being exported in jar file, I changed the path of the file in my ClassA.java to dependencies/inputs.txt. It didn't work in eclipse but I thought that it would work in jar because jar file is in classpath and dependencies folder is at the root of the jar file so the java launcher will be able to locate the dependencies folder and then inputs.txt file.

But unfortunately it is also not working.

2 Answers 2

6

You can't use FileInputStream to read a file packed inside a JAR - it's not a file any more. FileInputStream only works for actual disk files.

You need to read the resource using Class.getResourceAsStream (javadoc), e.g.

InputStream stream = getClass().getResourceAsStream("/dependencies/inputs.txt");

You leave off the test prefix because it's not in the JAR file structure.

Sign up to request clarification or add additional context in comments.

Comments

2

FileInputStream() will not read inside your jar, only files on the file system. Use .getClass().getResourceAsStream(resourcename) or .getClass().getClassLoader().getResourceAsStream(resourcename)

More info on the javadocs for class getResourceAsStream and classloader getResourceAsStream()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.