8

I have a folder structure like Project

  • src
  • --TestMain.java
  • bin
  • --TestMain.class
  • resources
  • --test.txt

As the whole project will be packaged into a jar file, I have to read a file from resources using getResourceAsStream. Although I have read through all questions about getResourceAsStream, I still can't get this working. Could anyone help? Thank you!

public class TestMain {

public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub

InputStream stream = TestMain.class.getResourceAsStream("\resources\test.txt");
    System.out.println(stream);
    BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream));
    StringBuilder builder = new StringBuilder();
    String line=null;
    while((line=bufRead.readLine())!=null){
        builder.append(line).append("\n");
    }
    System.out.println(builder.toString());

}
}
user3321400
  • 119
  • 1
  • 1
  • 6

4 Answers4

8

Basically, there are 2 different methods: ClassLoader.getResourceAsStream() and Class.getResourceAsStream(). These two methods will locate the resource differently.

In Class.getResourceAsStream(path), the path is interpreted as a path local to the package of the class you are calling it from. For example calling, String.getResourceAsStream("file.txt") will look for a file in your classpath at the following location: "java/lang/file.txt". If your path starts with a /, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling String.getResourceAsStream("/myfile.txt") will look at the following location in your class path ./file.txt.

ClassLoader.getResourceAsStream(path) will consider all paths to be absolute paths. So calling String.getClassLoader().getResourceAsString("myfile.txt") and String.getClassLoader().getResourceAsString("/file.txt") will both look for a file in your classpath at the following location: ./file.txt.

Every time the location, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.

IF you are loading the class from an Application Server, so your should use Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName) instead of this.getClass().getClassLoader().getResourceAsStream(fileName). this.getClass().getResourceAsStream() will also work.

TuGordoBello
  • 4,350
  • 9
  • 52
  • 78
Maheshbabu Jammula
  • 357
  • 1
  • 2
  • 11
  • Thank you for sharing - much appreciated! Does it mean we should always use ClassLoader.getResourceAsStream() instead of Class?getResourceAsStream()? – user3321400 Mar 12 '14 at 10:52
  • 1
    Copy paste this much? [Different ways of loading a file as an InputStream](https://stackoverflow.com/a/676273/1041046) – AaA Aug 03 '19 at 11:51
1

It seems the folder 'resources' is in your classpath, it is not need while getting resources under it,try below

InputStream stream = TestMain.class.getResourceAsStream("test.txt");
Safrain
  • 294
  • 1
  • 5
0

Is your test.txt in your classpath? I think that your test.txt is not inside your classpath. you have many solutions for to do that.

  • one could be give the fullpath of your file (c:/......)

  • verify when you generate .jar file your txt is inside .jar. if not include your resource folder inside your java project. when you include made a path directly for getResourceAsStream ("test.txt")

For disacoplated resource of your java project use a first option but if it not make sense use the second option .

Makoton
  • 443
  • 3
  • 14
  • When I generate .jar file, it seems the resources folder is not there. How do I include the resources folder in the .jar file? May I ask how to made a path directly to "text.txt" just in case I didn't do it right? I use Eclipse. Thank you. – user3321400 Mar 12 '14 at 06:12
  • well .... Rick click in your project/Build Path/ New source folder . Then paste your test.txt – Makoton Mar 12 '14 at 06:28
  • but i think if your run: mvn clean package he must generate a jar with the resource. If you use maven look: http://stackoverflow.com/questions/17617964/why-is-the-maven-jar-plugin-not-including-some-resources. you could read a cookbook about maven jar plugin too. good luck! – Makoton Mar 12 '14 at 06:38
0

Assume that you are using a httpclient:

        HttpClient httpClient = new HttpClient();

        httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);//your proxyHost & your proxyPort,

        GetMethod getMethod = new GetMethod(url);//your url,

        try {
            httpClient.executeMethod(getMethod);
            //strData = getMethod.getResponseBodyAsString();

            InputStream resStream = getMethod.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(resStream));
            StringBuffer resBuffer = new StringBuffer();
            String resTemp = "";
            while((resTemp = br.readLine()) != null){
                resBuffer.append(resTemp);
            }
            String response = resBuffer.toString();             
        } catch (Exception e) {
            System.out.println("HttpProxyManager.getResponse returns NULL");
            e.printStackTrace();
        } finally {
            getMethod.releaseConnection();
        }

the string response should be what you want to get.