Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getResource() to a file at runtime

I put some .txt files under the src folder (in the resources folder).

But I can't create a valid File at runtime from this resource.

String path = this.getClass().getResource("/resources/file.txt").getFile();
File file = new File(path);

if (!file.exists()) {
}

I run my program from eclipse. I didn't put in classpath anything.
I want my text files to be embedded into the .jar file, when I run my app I want to grab those files and copy them into some location.

UPDATE

if I do InputStream is = getClass().getResourceAsStream("/resources/file.txt");

I get the stream!!

like image 816
kenny Avatar asked Dec 21 '25 14:12

kenny


1 Answers

As you already discovered yourself soon after posting your question, this works:

InputStream is = getClass().getResourceAsStream("/resources/file.txt");

The reason this works, while your original code doesn't, is because a "file" inside in a zip file (a jar file is a zip file) is not a real file until it has been extracted. But extracting the file is what you are trying to do, so at that point in your program, it's not a real file. So this question is an X-Y problem: you wanted to create a File object, but that wasn't possible - you needed to refer back to what you were originally trying to do, which was read from the zip entry.

like image 125
Robin Green Avatar answered Dec 24 '25 02:12

Robin Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!