1

I have download.sh file in my src/main/resource folder in maven project and I am reading it through below code

 ClassLoader classLoader = getClass().getClassLoader();
 File file = new File(classLoader.getResource("download.sh").getFile());

The file is reading when I run this as the standalone application.

If I run this as application using jar ex:-

java -jar runScript.jar SCHEMA_NAME

/Users/IdeaProjects/RunScript/target/file:/Users/IdeaProjects/RunScript/target/RunScripts.jar!/download.sh": error=2, No such file or directory

Can anyone help me in reading file from resource when executing with jar

Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42
Ganesh
  • 167
  • 1
  • 7
  • 21

3 Answers3

1

I think this error happens when you try to read the file. This is because resources inside your jar are not files but streams. So you should use

getClass().getResourceAsStream("download.sh");

and then read that stream, for example:

InputStream resourceStream = getClass().getResourceAsStream("download.sh")
BufferedReader br = new BufferedReader(new InputStreamReader(resourceStream));
String line;
while ((line = br.readLine()) != null) {
    // do something
    System.out.println(line);
}
Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42
0

I think you are not packaging your resources along with your jar. Please verify your jar contains the resource file (download.sh) with

jar -tvf <yourfile.jar> | grep -i download 
  • resource folder not created in jar. But all the files included in the immediate directory – Ganesh Dec 21 '17 at 03:40
  • 1
    @Ganesh That doesn't make sense. If the resources aren't in the JAR, why are you using `ClassLoader.getResource()`? – user207421 Dec 21 '17 at 06:07
  • @Ganesh, If you are using maven, try these links : https://stackoverflow.com/questions/6316462/maven-resource-files-put-java-class-files-and-property-files-in-same-directory (or) https://stackoverflow.com/questions/5637532/maven-how-to-place-resource-file-together-with-jar – Sivaswami Jeganathan Dec 25 '17 at 12:44
0

Resources are not files. You can get their URLs, or input streams, but nothing you can do will turn a resource in a JAR file into a file on the disk that you can use with File. Short of unpacking the JAR file, that is.

user207421
  • 305,947
  • 44
  • 307
  • 483