-1

My java program has a reference to one of the text file. I have added the resource folder to build path, but still I'm not able to access the file in my program.

package first;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class First {

    public static void main(String[] args) {
        InputStream inputStream = 
                First.class.getResourceAsStream("message.properties");
        if (inputStream == null)
        {
            System.out.println("IO stream is null");
            return;
        }
        String result = null;
        try {
            result = inputStreamToString(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(result);
    }
    

output

IO Stream is null
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • can you double check the path of ```message.properties```? Next, [in the official docs,](https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getResourceAsStream-java.lang.String-) it says that the resource will not be loaded if it is a non ```.class``` value. you are trying to load a properties file, there could be an issue with that. – berlin Feb 19 '21 at 09:24

1 Answers1

-2
First.class.getResourceAsStream("/message.properties");

E.g. for standard manve project you have resources folder. When compile to jar, it will move to the root of it. So adding / will start searchig from the root of the jar or target folder.

P.S. Do not forget to close the InputStream!

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35