1

In my Eclipse JUNIT test I have several text input files that are opened by

new BufferedReader(new FileReader(inputFileName));.  

They are placed in the root directory of the project After exporting this project to jar these files are placed to the jar root directory.
I run the JUNIT test from LINUX as

java -cp "<my jar>:junit-4.8.2.jar:jaxb-impl.jar" junit.textui.TestRunner <test class name>

However, in this case I am getting java.io.FileNotFoundException What is the best way to fix this problem on LINUX and at the same time still able to run the tests from Eclipse?

Alex
  • 7,007
  • 18
  • 69
  • 114

3 Answers3

2

Use Class#getResourceAsStream() method to load classpath resources:

InputStream is = this.getClass().getResourceAsStream("myfile.txt");

You can convert it to Reader interface using InputStreamReader adapter.

hoaz
  • 9,883
  • 4
  • 42
  • 53
  • The same comment as for the previous answer - can I have the same directory structure? – Alex May 14 '13 at 17:05
  • Not sure that I understand your question, but you said that your file is in JAR. So it is effectively available by the class loader – hoaz May 14 '13 at 17:27
  • yes, but this jar is in the root directory of this Jar. I need to move it to src direcotry (sourcepath) to invoke the class loader – Alex May 14 '13 at 20:04
  • usually you put all required resources to src/main/resources and they are packed into JAR together with classes, if you use this file for testing purposes only, you need to put it into src/test/resources – hoaz May 14 '13 at 20:25
1

What I want was achieved by adding * to the classpath and putting properties file into run directory. This feature started in Java 6. Then the properties file is achievable in classpath and is achieved both from Eclipse and command prompt running. It is a little different from my question – the properties file is not in jar, but that is what is needed. Plus, one can edit the properties file outside of Eclipse

Alex
  • 7,007
  • 18
  • 69
  • 114
0

You could use the Class method getResourceAsStream

There's also an other issue on stackoverflow see: getResourceAsStream() vs FileInputStream

Community
  • 1
  • 1
ceasaro
  • 595
  • 6
  • 11
  • Thank you. In this case I will need to move files to a directory that is available by the class loader. Is it possible to have the same directory structure as now? – Alex May 14 '13 at 17:04