본문 바로가기

 ㅤㅤㅤ

How to really read text file from classpath in Java 본문

プログラミング/JAVA

How to really read text file from classpath in Java

ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ 2017. 7. 24. 18:01

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.

shareimprove this question

答えが見つからない?日本語で聞いてみましょう。

up vote454down voteaccepted

With the directory on the classpath, from a class loaded by the same classloader, you should be able to use either 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 those aren't working, that suggests something else is wrong.

So for example, 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 directory structure:

code
    dummy
          Test.class
txt
    SomeTextFile.txt

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

java -classpath code:txt dummy.Test

Results:

true
true
shareimprove this answer
   
You mixed relative and absolute paths up. A path that starts with "/" is absolute (i.e. starts from whatever is listed in CLASSPATH). All other paths are relative to the package of the class on which you call getResourceAsStream() – Aaron Digulla Sep 23 '09 at 7:25
11 
No, you broke my example. I'll edit the comments to make them clearer, but the point is that using ClassLoader all paths are assumed to be absolute already. There's nothing for them to be relative to. – Jon Skeet Sep 23 '09 at 7:57
6 
Also do not use Java.IO.File.Separator. It wont work on windows. If you are running this code on windows it still has to be '/' and not '\' – Pradhan Jun 14 '13 at 17:56
20 
@Pradhan: No, you shouldn't be using File.Separator - because you're not asking for a file, you're asking for a resource. It's important to understand that the abstraction involved isn't the file system. – Jon Skeet Jun 14 '13 at 17:59
1 
@jagdpanzer: Well it's only for classes which are loaded by the same classloader, basically - and it's because Class.getResourceAsStream is really a convenience method for calling ClassLoader.getResourceAsStream, but with the additional feature of "relative" resources. If you're specifying an absolute resource, then any call using the same classloader will do the same thing. – Jon Skeet Nov 5 '15 at 18:07

When using the Spring Framework (either as a collection of utilities or container - you do not need to use the latter functionality) you can easily use the Resource abstraction.

Resource resource = new ClassPathResource("com/example/Foo.class");

Through the Resource interface you can access the resource as InputStreamURLURI or File. Changing the resource type to e.g. a file system resource is a simple matter of changing the instance.

shareimprove this answer
3 
Could you please provide a sample code on how this can be used in file I/O? I can't find a decentexplicit and straightforward way on how to use it in the Internet :(((( – user1685185 Feb 11 '14 at 16:00
   
Works like a charm. The provided one liner is all you need. Use the stream parsing from other examples if you don't know how to get a string from the stream. – Joseph Lust Feb 16 '14 at 18:14
   
I had a bit of trouble figuring out exactly what to do with the resource variable as well. I've edited the answer with a bit more detail – DavidZemon Dec 2 '14 at 14:10
   
I was already using Spring and trying the "pure java" way. It was killing me, the differences between getResource, getResourceAsStream, etc, with no good working examples. This is a perfect example of encapsulation, so I don't have to care. – Adam Edison - Music Educator Jan 19 at 16:08

This is how I read all lines of a text file on my classpath, using Java 7 NIO:

...
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

...

Files.readAllLines(
    Paths.get(this.getClass().getResource("res.txt").toURI()), Charset.defaultCharset());

NB this is an example of how it can be done. You'll have to make improvements as necessary. This example will only work if the file is actually present on your classpath, otherwise a NullPointerException will be thrown when getResource() returns null and .toURI() is invoked on it.

Also, since Java 7, one convenient way of specifying character sets is to use the constants defined in java.nio.charset.StandardCharsets (these are, according to their javadocs, "guaranteed to be available on every implementation of the Java platform.").

Hence, if you know the encoding of the file to be UTF-8, then specify explicitly the charset StandardCharsets.UTF_8

shareimprove this answer
   
Thank you for the NIO solution - so few people use this great API it is a shame. – mvreijn Apr 14 '15 at 18:50
2 
To read into a single String try. new String(Files.readAllBytes(Paths.get(MyClass.class.getResourc‌​e(resource).toURI())‌​)); – Theo Briscoe Jul 23 '16 at 12:03
1 
Best solution for me, as it doesn't need any dependencies, like Spring or Commons IO. – Bernie Sep 25 '16 at 9:44

Please try

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

Your tries didn't work because only the class loader for your classes is able to load from the classpath. You used the class loader for the java system itself.

shareimprove this answer
   
Not sure about the "/" though. A relative path might work better in this case. – VonC Sep 23 '09 at 6:53
3 
If you use it without "/" you are looking for your file inside the package of "this". – tangens Sep 23 '09 at 7:04
1 
InputStream file = this.getClass().getResourceAsStream("SomeTextFile.txt"); InputStream file = this.getClass().getResourceAsStream("/SomeTextFile.txt"); InputStream file = this.getClass().getResourceAsStream("//SomeTextFile.txt"); None of the above worked :( – Chaitanya MSVSep 23 '09 at 7:37
   
@Chaitanya: Can you run the example from John Skeet's answer? – Aaron Digulla Sep 23 '09 at 7:40

To actually read the contents of the file, I like using Commons IO + Spring Core. Assuming Java 8:

try (InputStream stream = new ClassPathResource("package/resource").getInputStream()) {
    IOUtils.toString(stream);
}

Alternatively:

InputStream stream = null;
try {
    stream = new ClassPathResource("/log4j.xml").getInputStream();
    IOUtils.toString(stream);
} finally {
    IOUtils.closeQuietly(stream);
}
shareimprove this answer
   
What about closing the inputstream? – Stephan Apr 21 '16 at 15:32
   
Holy cow, thanks for pointing that out! I've been doing this wrong all along... – Pavel Apr 22 '16 at 13:10

To get the class absolute path try this:

String url = this.getClass().getResource("").getPath();
shareimprove this answer
   
And then what? That information is no use by itself. – EJP Apr 14 '15 at 22:41
   
This information was perfect. I was only missing getPath()! – Patrick Aug 16 '15 at 16:11
   
@Patrick This answer does not provide the 'class absolute path'. It provides a URL. Not at all the same thing.– EJP Oct 25 '15 at 9:33 

Somehow the best answer doesn't work for me. I need to use a slightly different code instead.

ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("SomeTextFile.txt");

I hope this help those who encounters the same issue.

shareimprove this answer
   
thanks this helped me in Junit – To Kra Aug 20 '15 at 13:50
   
This helped me on Android as well where a class was loaded by the application loader, but a key that it needed was lazy loaded in the UI thread. – asokan Jul 4 '16 at 22:35

You say "I am trying to read a text file which is set in CLASSPATH system variable." My guess this is on Windows and you are using this ugly dialog to edit the "System Variables".

Now you run your Java program in the console. And that doesn't work: The console gets a copy of the values of the system variables once when it is started. This means any change in the dialog afterwards doesn't have any effect.

There are these solutions:

  1. Start a new console after every change

  2. Use set CLASSPATH=... in the console to set the copy of the variable in the console and when your code works, paste the last value into the variable dialog.

  3. Put the call to Java into .BAT file and double click it. This will create a new console every time (thus copying the current value of the system variable).

BEWARE: If you also have a User variable CLASSPATH then it will shadow your system variable. That is why it is usually better to put the call to your Java program into a .BAT file and set the classpath in there (using set CLASSPATH=) rather than relying on a global system or user variable.

This also makes sure that you can have more than one Java program working on your computer because they are bound to have different classpaths.

shareimprove this answer

To read the contents of a file into a String from the classpath, you can use this:

private String resourceToString(String filePath) throws IOException, URISyntaxException
{
    try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath))
    {
        return IOUtils.toString(inputStream);
    }
}

Note:
IOUtils is part of Commons IO.

Call it like this:

String fileContents = resourceToString("ImOnTheClasspath.txt");
shareimprove this answer

Don't use getClassLoader() method and use the "/" before the file name. "/" is very important

this.getClass().getResourceAsStream("/SomeTextFile.txt");
shareimprove this answer
   
Using the leading / has exactly the same effect as using the getClassLoader() method. – EJP Oct 25 '15 at 9:32

I am using webshpere application server and my Web Module is build on Spring MVC. The Test.properties were located in the resources folder, i tried to load this files using the following:

  1. this.getClass().getClassLoader().getResourceAsStream("Test.properties");
  2. this.getClass().getResourceAsStream("/Test.properties");

None of the above code loaded the file.

But with the help of below code the property file was loaded successfully:

Thread.currentThread().getContextClassLoader().getResourceAsStream("Test.properties");

Thanks to the user "user1695166".

shareimprove this answer
1 
Welcome to Stack Overflow! Please don't add "thanks" as answers even if you're also partially providing how your solution went, if your solutions is the same as another post it doesn't need to be added. After you've invested some time in the site you'll gain sufficient privileges to upvote answers you like, which is the Stack Overflow way of saying thank you. – SuperBiasedMan Aug 10 '15 at 13:26

you have to put your 'system variable' on the java classpath.

shareimprove this answer
   
I put System variable itself. – Chaitanya MSV Sep 23 '09 at 7:36
   
The 'system variable' is the Java CLASSPATH. Answer doesn't make sense. – EJP Apr 14 '15 at 22:42 
   
Totally true... did not even remember writing this answer :) – Salandur Apr 15 '15 at 20:20
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile

{
    /**
     * * feel free to make any modification I have have been here so I feel you
     * * * @param args * @throws InterruptedException
     */

    public static void main(String[] args) throws InterruptedException {
        // thread pool of 10
        File dir = new File(".");
        // read file from same directory as source //
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                // if you wanna read file name with txt files
                if (file.getName().contains("txt")) {
                    System.out.println(file.getName());
                }

                // if you want to open text file and read each line then
                if (file.getName().contains("txt")) {
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(
                                file.getAbsolutePath());
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = new BufferedReader(
                                fileReader);
                        String line;
                        // get file details and get info you need.
                        while ((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            // here you can say...
                            // System.out.println(line.substring(0, 10)); this
                            // prints from 0 to 10 indext
                        }
                    } catch (FileNotFoundException ex) {
                        System.out.println("Unable to open file '"
                                + file.getName() + "'");
                    } catch (IOException ex) {
                        System.out.println("Error reading file '"
                                + file.getName() + "'");
                        // Or we could just do this:
                        ex.printStackTrace();
                    }
                }
            }
        }

    }

}
shareimprove this answer
   
Doesn't answer the question in any way. – EJP Oct 25 '15 at 9:31


Comments