getResource() to a file at runtime

kenny picture kenny · Nov 16, 2011 · Viewed 15.1k times · Source

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!!

Answer

Robin Green picture Robin Green · Dec 3, 2018

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.