从文件中获取InputStream,该文件可能(也可能不)在类路径中



只是想知道读取类路径中的文件的最佳方式。

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

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

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

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

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

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"目录的根等)。

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

好吧,我只需要使用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
}

请参阅此处以从jar中提取资源。

使用弹簧时,org.springframework.core.io.DefaultResourceLoader是一种解决方案:

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

相关内容

最新更新