简体   繁体   中英

unable to read file using getResourceAsStream

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());

}
}

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.

似乎文件夹“资源”在您的类路径中,在其下获取资源时不需要它,请尝试以下

InputStream stream = TestMain.class.getResourceAsStream("test.txt");

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM