getResource() to a file at runtime

2019-01-28 23:07发布

问题:

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

回答1:

You said that you are using eclipse, and that you dragged and dropped your text files into the "src" package. "src" is not a package. It is simply a file system directory. By default in a Java project in eclipse all your source code is stored in a directory called "src" and all your .class files are stored in a directory called "bin". getClass().getResource() resolves to the location of your .class files. You must move the text files into the "bin" directory.

What package is your class in?

I wrote very similar code to yours in the default package and ran it in eclipse.

import java.io.File;

public class ResourceTest {
    public static void main(String[] args) {
        ResourceTest rt = new ResourceTest();
        rt.openFile();
    }

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

        System.out.println(path);
        System.out.println(file.getAbsolutePath());
        System.out.println(file.exists());
    }
}

I see this output:

/C:/Users/rab29/Documents/eclipse/Overflow/bin/resources/file.txt
C:\Users\rab29\Documents\eclipse\Overflow\bin\resources\file.txt
true


回答2:

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.