简体   繁体   English

无法使用相对路径将文件从jar读取到FileInputStream中

[英]Unable to read a file from a jar into a FileInputStream using a relative path

Given I am able to load my mail.properties file such as : 鉴于我能够加载我的mail.properties文件,例如:

ResourceBundle rb = ResourceBundle.getBundle("META-INF.mail");
System.out.prinltn("subject :" + rb.getString("email.subject")); //output : 'subject : Job Application'

However I am unable to read; 但是我看不懂。 in the same method; 用同样的方法 my mail.properties file as a FileInputStream . 我的mail.properties文件作为FileInputStream I have tried all these options none of them worked and I am always getting a FileNotFoundException : 我已经尝试了所有这些选项,但它们都不起作用,而且我总是收到FileNotFoundException

FileInputStream fis = new FileInputStream("META-INF/mail.properties");
FileInputStream fis = new FileInputStream("META-INF//mail.properties");
FileInputStream fis = new FileInputStream("META-INF\\mail.properties");

The folder META-INF exists within a jar that is loaded at build time : META-INF文件夹存在于在构建时加载的jar中:

在此处输入图片说明

Any help will be more than appreciated. 任何帮助将不胜感激。

The problem is FileInputStream() will look for paths relative to current directory. 问题是FileInputStream()将查找相对于当前目录的路径。 Since your META-INF is inside the imported jar, it won't be able to find it. 由于您的META-INF在导入的jar内,因此无法找到它。

As per this post , you have following options: 根据这篇文章 ,您有以下选择:

  1. Specify an absolute filename 指定一个绝对文件名
  2. Specify a relative filename which takes into account where you're running this 指定一个相对文件名,该文件名考虑了您在其中运行的位置
  3. Bundle the file as a resource and use Class.getResourceAsStream or similar 将文件捆绑为资源,并使用Class.getResourceAsStream或类似文件

check it out for more details. 请查看更多详细信息。 My question if you are able to load it with ResourceBundle , why are you trying to reload it in a different way? 我的问题是,如果您能够使用ResourceBundle加载它,为什么要尝试以其他方式重新加载它?

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

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