您的位置:首页 > 编程语言 > Java开发

java中读取文件路径问题

2015-08-28 17:16 483 查看
在读配置文件的时候,遇到找不到该文件。明明就在这里,相对位置也对了,怎么就是找不到了呢。下面来解惑:
我们知道,在java中读取文件至少有以下两种方式,我这里指的是本地文件,网络流不计在内。


方式一:
File file = new File(path);
FileInputStream fis = new FileInputStream(file);


方式二:
FileInputStream fis = 所在文件类名.class.getResourceAsStream(path);


背景描述:我有一个配置文件weixin.properties,直接放在src下。现在我要在 com.hww.path.FilePathTest 这个类中来读取 weixin.properties这个文件。


//使用第一种方式:
//路径是相对于所在项目的,是文件路径,是磁盘中的位置。故路径前面要加上src。
File file = new File("src/weixin.properties");
FileInputStream in  = new FileInputStream(file);


//使用第二种方式
//相对路径就变成了bin(确切叫classpath)路径下的类路径了
//根路径就是classpath了,也就是编译路径了
InputStream ins1 =  FilePathTest.class.getResourceAsStream("../../../weixin.properties");

InputStream ins2 = FilePathTest.class.getResourceAsStream("/weixin.properties");

//我们可以通过下面的方法打印出路径来
String url1 = FilePathTest.class.getResource("/").getPath();
System.out.println(url1); //输出: /E:/workspace/JavaNet/bin/

String url2 = FilePathTest.class.getResource(".").getPath();
System.out.println(url2); // 输出:/E:/workspace/JavaNet/bin/com/hww/path/


另外补充一下,根路径(/)是不能用File.separator表示。只能用于分割之间。

如图:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: