简体   繁体   English

无法使用 getResourceAsStream 读取文件

[英]unable to read file using getResourceAsStream

I have a folder structure like Project我有一个像 Project 这样的文件夹结构

  • src源文件
  • --TestMain.java --TestMain.java
  • bin垃圾桶
  • --TestMain.class --TestMain.class
  • resources资源
  • --test.txt --test.txt

As the whole project will be packaged into a jar file, I have to read a file from resources using getResourceAsStream.由于整个项目将被打包成一个 jar 文件,我必须使用 getResourceAsStream 从资源中读取一个文件。 Although I have read through all questions about getResourceAsStream, I still can't get this working.尽管我已经通读了有关 getResourceAsStream 的所有问题,但我仍然无法解决这个问题。 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() .基本上,有两种不同的方法: ClassLoader.getResourceAsStream()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.Class.getResourceAsStream(path) ,路径被解释为调用它的类的包的本地路径。 For example calling, String.getResourceAsStream("file.txt") will look for a file in your classpath at the following location: "java/lang/file.txt" .例如,调用String.getResourceAsStream("file.txt")将在类路径中的以下位置查找文件: "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.因此,调用String.getResourceAsStream("/myfile.txt")将查看类路径中的以下位置 ./file.txt。

ClassLoader.getResourceAsStream(path) will consider all paths to be absolute paths. ClassLoader.getResourceAsStream(path)会将所有路径视为绝对路径。 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 .因此,调用String.getClassLoader().getResourceAsString("myfile.txt")String.getClassLoader().getResourceAsString("/file.txt")都会在类路径中的以下位置查找文件: ./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.每次定位时,它可能是文件系统本身中的一个位置,也可能是相应 jar 文件中的一个位置,具体取决于您从中加载资源的 Class 和/或 ClassLoader。

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) .如果您从应用程序服务器加载类,那么您应该使用Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName)而不是this.getClass().getClassLoader().getResourceAsStream(fileName) this.getClass().getResourceAsStream() will also work. this.getClass().getResourceAsStream()也可以工作。

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

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

Is your test.txt in your classpath?你的 test.txt 在你的类路径中吗? I think that your test.txt is not inside your classpath.我认为您的 test.txt 不在您的类路径中。 you have many solutions for to do that.你有很多解决方案可以做到这一点。

  • one could be give the fullpath of your file (c:/......)一个可以提供文件的完整路径(c:/......)

  • verify when you generate .jar file your txt is inside .jar.验证生成 .jar 文件时,您的 txt 是否在 .jar 中。 if not include your resource folder inside your java project.如果没有在你的java项目中包含你的资源文件夹。 when you include made a path directly for getResourceAsStream ("test.txt")当您直接为 getResourceAsStream ("test.txt") 创建路径时

For disacoplated resource of your java project use a first option but if it not make sense use the second option .对于 Java 项目的不兼容资源,请使用第一个选项,但如果没有意义,请使用第二个选项。

Assume that you are using a httpclient:假设您使用的是 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.字符串响应应该是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用getResourceAsStream读取XML文件 - How to read a XML file using getResourceAsStream ExceptionInInitializerError - 使用getResourceAsStream读取jar包中的文件 - ExceptionInInitializerError - using getResourceAsStream to read a file in a jar package 使用getResourceAsStream使用他的完整路径读取Android文件 - Using getResourceAsStream to read an Android file using his full-path 如何使用getResourceAsStream在J2ME中读取文件 - How to read file in J2ME using getResourceAsStream 无法使用getResourceAsStream加载文件 - Cannot Load the file using getResourceAsStream 使用getResourceAsStream在m子中注入文件 - Injecting file in mule using getResourceAsStream 为什么我无法在类路径中使用getResourceAsStream读取属性文件(在WEB-INF / lib下) - Why I cant read properties file using getResourceAsStream when it is in classpath (under WEB-INF/lib) 当我使用getResourceAsStream读取Android Studio中的属性文件时,获取“ null” - Get “null” when I'm using getResourceAsStream to read properties file in Android Studio 如何使用Java方法Class.getResourceAsStream()从jar中读取UTF-8文本文件? - How can I read a UTF-8 text file from a jar using the Java method Class.getResourceAsStream()? 如何通过带有相对路径的getResourceAsStream读取zip文件? - How to read zip file through getResourceAsStream with relative path?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM