Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)

I am trying to read a text file which is set in CLASSPATH system variable. Not a user variable.

I am trying to get input stream to the file as below:

Place the directory of file (D:\myDir)in CLASSPATH and try below:

InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt");

InputStream in = this.getClass().getClassLoader().getResourceAsStream("/SomeTextFile.txt");

InputStream in = this.getClass().getClassLoader().getResourceAsStream("//SomeTextFile.txt");

Place full path of file (D:\myDir\SomeTextFile.txt)in CLASSPATH and try the same above 3 lines of code.

But unfortunately NONE of them are working and I am always getting null into my InputStream in.

1 Answer

0 votes
by (46k points)

With the index on the classpath, from a class loaded by the identical classloader, you should be able to try each of:

// From ClassLoader, all paths are "absolute" already - there's no context

// from which they could be relative. Therefore you don't need a leading slash.

InputStream in = this.getClass().getClassLoader()

                                .getResourceAsStream("SomeTextFile.txt");

// From Class, the path is relative to the package of the class unless

// you include a leading slash, so if you don't want to use the current

// package, include a slash like this:

InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");

If these aren't operating, that implies something else is incorrect.

So for instance, take this code:

package dummy;

import java.io.*;

public class Test

{

    public static void main(String[] args)

    {

        InputStream stream = Test.class.getResourceAsStream("/SomeTextFile.txt");

        System.out.println(stream != null);

        stream = Test.class.getClassLoader().getResourceAsStream("SomeTextFile.txt");

        System.out.println(stream != null);

    }

}

And this index structure:

code

    dummy

          Test.class

txt

    SomeTextFile.txt

And then (practicing the Unix path separator as I'm on a Linux box):

java -classpath code:txt dummy.Test

Returns:

true

true

Related questions

0 votes
1 answer
asked Oct 27, 2019 in Java by Shubham (3.9k points)
+15 votes
2 answers
asked May 29, 2019 in Java by adam96 (800 points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...