【问题标题】:Get InputStream from a file, that may (or not) be in the classpath [duplicate]从可能(或不在)类路径中的文件中获取 InputStream [重复]
【发布时间】:2012-09-06 17:32:26
【问题描述】:

只是想知道哪种方法是读取可能位于类路径中的文件的最佳方式。

我唯一拥有的是文件路径的属性。例如:

  • filepath=classpath:com/mycompany/myfile.txt
  • filepath=file:/myfolder/myfile.txt

从该属性加载 InputStream 的最佳方式是什么?

【问题讨论】:

  • 您需要具体说明吗?我会搜索类路径,如果不存在,则从文件系统中读取。

标签: java file io


【解决方案1】:

好吧,我只需使用 String 方法 startsWith(String sequence) 并检查它是否以 classpathfilepath 开头,然后从那里调用适当的方法来执行工作:

String str=//extracted property tag
if(str.startsWith("filepath")) {
 //simply intialize as URL and get inputstream from that
 URL url =new URL(str);
 URLConnection uc = url.openConnection(); 
 InputStream is=uc.getInputStream();
} else if(str.startsWith("classpath")) {
//strip the classpath  and then call method to extract from jar
}

请参阅here 从 jar 中提取资源。

【讨论】:

    【解决方案2】:

    您可以使用URL 方法openStream,它返回一个InputStream,您可以使用它来读取您的文件。该 URL 将适用于 JAR 内部和外部的文件。请注意使用有效的 URL。

    【讨论】:

    • URL 给我原因:java.net.MalformedURLException:未知协议:类路径
    • 是的,java 默认不支持“classpath”url 类型。一些应用服务器添加了对此的支持。
    【解决方案3】:

    您必须手动检测它。完成此操作后,以输入流的形式从类路径中获取资源:

    class Example {
        void foo() {
            try (InputStream in = Example.class.getResourceAsStream("/config.cfg")) {
                // use here. It'll be null if not found.
            }
        }
    }
    

    注意:如果没有前导斜杠,它相对于包含您的 Example.class 文件的同一目录(如果需要,在 jar 内)。带有前导斜杠的它是相对于类路径的根目录(jar 的根目录、'bin' 目录的根目录等)。

    当然,没有办法获得输出流;通常,类路径中的大多数条目都是不可写的。

    【讨论】:

    • springs好像有这个解析器,可以用吗?
    • 很好的更正,@JoopEggen - 我编辑了 sn-p,如果下次出现,请随时用类似的东西编辑我的答案:)
    【解决方案4】:

    使用spring时org.springframework.core.io.DefaultResourceLoader是一个解决方案:

    @Resource DefaultResourceLoader defaultResourceLoader;
    defaultResourceLoader.getResource(path).getInputStream()
    

    【讨论】:

      猜你喜欢
      • 2018-07-12
      • 1970-01-01
      • 2013-06-24
      • 2020-01-07
      • 2014-04-08
      • 1970-01-01
      • 2020-02-11
      相关资源
      最近更新 更多