简体   繁体   中英

How to import a file from resources folder in Eclipse for Java

I have a file in my resources folder in my project in Eclipse. I need a way in which to load this document into my Java file. Preferable representation would be in an InputStream.

I tried the following based on some searching but it does not seem to be working and I am not sure why (I get null), any help appreciated

InputStream is = getClass().getResourceAsStream("/Project/resources/BlankPDF.pdf");

Ensure the resource is located in the same folder as your compiled classes. I don't use Eclipse, but Netbeans automatically creates a "classes" folder upon build. Classes that are in a package, ie org.website.PDFReader , will have a set of subdirectories under the 'classes' folder, following the fully qualified name of the class (ie package name + class name). Regardless, the 'parent directory' for these packaged classes is still the 'classes' folder.

For the time being, place your resources in that classes folder manually. There is almost certainly a way to make Eclipse automatically copy resources into the appropriate folder upon build (see below).

Finally, in your code, remove the leading "/" from "/Project/..."

When you remove that leading "/", it makes the resource location relative to the parent directory of your Class's class loader - in this example, the 'classes' folder. Keeping that forward-slash makes the resource location 'absolute' - not relative to any parent directory.

Edit: The following question should help out with the more Eclipse-specific details of this process: Java in Eclipse: Where do I put files on the filesystem that I want to load using getResource? (eg images for an ImageIcon) . Make sure to check out the first comment on the accepted answer, as well.

The string which you pass as an argument to getResourceAsStream has to be either the location relative to the class you call getResourceAsStream from, or absolute wrt any of your source folders, with a leading / .

So if resources is a source folder in your project (marked with a little package-like symbol in Eclipse) then getClass().getResourceAsStream("/BlankPDF.pdf") should work.

Example: Say you have the following folders and packages in your project, source folders being marked with a * :

Project
    src*
        com.package.foo
            MyClass.java
    resources*
        BlankPDF.pdf

Then both MyClass.class.getResourceAsStream("/BlankPDF.pdf") (leading / , absolute) and MyClass.class.getResourceAsStream("../../../BlankPDF.pdf") (no leading / , relative) should get you the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM