idea FileNotFoundExceptoion异常

idea 文件读取问题FileNotFoundException

出现此问题大部分原因,源于文件路径错误

文件读取文件方式
  1. Test类测试读取fileSources.properties
    在这里插入图片描述
InputStream inputStream = new FileInputStream("src/main/resources/fileSources.properties");
OutputStream outputStream = new FileOutputStream("src/main/resources/fileSources.properties");

fileSources.properties文件位于src/main/resources目录下,所以这个相对路径是相对于整个项目.

最大问题: 项目打包成jar包后,src目录就不存在了,因此最好不要采用此方法

  1. 依旧使用Test类测试读取fileSources.properties
    在这里插入图片描述
//获取文件路路径
String path = Test.class.getResource("../classes/fileSources.properties").getPath();
OutputStream outputStream = new FileOutputStream(path);
InputStream inputStream = new FileInputStream(path);

首先,Test.class是Test.java编译后的字节码文件,此文件被idea编译后位于哪???
(target/test-classes目录下)
然后fileSources.properties文件又在哪里???
(2个,一个位于src/main/resources目录下,另外一个位于target/classes)使用哪一个?
为避免出现上一示例的问题,很明显使用后面一个

相对路径详解:

../classes/fileSources.properties
父级目录/clsses目录/fileSources.properties文件

简而言之,相对于 Test.class文件的位置;

  1. 测试类和文件与上面一致
    在这里插入图片描述
 String path = Test.class.getClassLoader().getResource("fileSources.properties").getPath();
 InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("fileSources.properties");
  OutputStream out = new FileOutputStream(path);

使用类加载器获取文件路径,Test.class.getClassLoader() 获取当前类的类加载器。getResource()方法返回URL对象,调用URL对象的getPath()方法获取路径。
类加载器定位目录(个人称法)为classes目录, 所以getResource()方法的参数为“fileSources.properties”;
假设要使用该方式读取file目录下的文件(代码如下):

    String path = Test.class.getClassLoader().getResource("file/buses.json").getPath();
    OutputStream out = new FileOutputStream(path);
  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值