Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
950 views
in Technique[技术] by (71.8m points)

java - ClassLoader getResourceAsStream returns null

My project directory structure (in Eclipse):

MyProject/
    src/        --> "source directory" on Eclipse's classpath/buildpath
        com.me.myapp
            Driver
            myconfig.txt

In Driver, I have the following code:

public class Driver {
    public static void main(String[] args) {
        InputStream is = ClassLoader.getSystemClassLoader.getResourceAsStream("myconfig.txt");
        if(is == null)
            System.out.println("input stream is null");
        else
            System.out.println("input stream is NOT null :-)");
    }
}

When I run this I get the following console output:

input stream is null

Why? Have I placed myconfig.txt in an incorrect location? Am I using the ClassLoader API incorrectly? Something else? Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If it's in the same package use

InputStream is = Driver.class.getResourceAsStream("myconfig.txt");

The way you have it

InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("myconfig.txt");

It's looking for the file in the root of the classpath. You could use

InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("com/me/myapp/myconfig.txt");

The rules for searching are explained in the javadoc of ClassLoader#getResource(String) and the javadoc of Class#getResource(String).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...