【问题标题】:Get a file from a given classpath从给定的类路径获取文件
【发布时间】:2013-08-28 14:52:13
【问题描述】:
public String getQuery(String nameFile, Package pathFile)
{
   //   How to get on InputStrem nameFile and pathFile
}

我无法通过类加载器实现它

String path = getClass().getPackage().getName().replace('.', File.pathSeparatorChar);
String file = path + "file.txt";
InputStream in = this.getClass().getClassLoader().getResourceAsStream(file);

返回 = null

【问题讨论】:

    标签: java io classpath inputstream


    【解决方案1】:

    pathSeparatorChar 在 Unix 上是 :,在 Windows 上是 ;。它与所有平台上用于从 ClassLoader 加载资源的 char 无关,即/

    此外,您忘记了路径和文件名之间的分隔符。应该是

    String path = getClass().getPackage().getName().replace('.', '/');
    String file = path + "/file.txt";
    InputStream in = this.getClass().getClassLoader().getResourceAsStream(file);
    

    或者,更简单,因为Class 有一个方法可以直接从与类相同的包中加载资源:

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

    【讨论】:

    • InputStream in = this.getClass().getResourceAsStream("file.txt");是作品。我需要摆脱另一个包裹。
    • 我在你评论时添加了这个完全相同的建议 :-)
    • 谢谢,您的回答很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 2018-05-31
    • 2011-11-16
    相关资源
    最近更新 更多