java 读取某包下的文件,在Java中的包下的文件从哪里读取?

I have a properties file contains the file name only say file=fileName.dat. I've put the properties file under the class path and could read the file name(file.dat) properly from it in the mainClass. After reading the file name I passed the file name(just name not the path) to another class under a package say pack.myClass to read that file. But the problem is pack.myClass could not get the file path properly. I've put the file fileName.dat both inside and outside the packagepack but couldn't make it work.

Can anybody suggest me that where to put the file fileName.dat so I can read it properly and the whole application would be portable too.

Thanks!

The code I'm using to read the config file and getting the file name:

Properties prop = new Properties();

InputStream in = mainClass.class.getResourceAsStream("config.properties");

prop.load(in);

in.close();

myClass mc = new myClass();

mc.readTheFile(prop.getProperty("file"));

/*until this code is working good*/

Then in myClass which is under package named pack I am doing:

public void readTheFile(String filename) throws IOException {

FileReader fileReader = new FileReader(filename); /*this couldn't get the file whether i'm putting the file inside or outside the package folder */

/*after reading the file I've to do the BufferReader for further operation*/

BufferedReader bufferedReader = new BufferedReader(fileReader);

解决方案

I assume that you are trying to read properties file using getResource method of class. If you put properties file on root of the classpath you should prefix file name with '/' to indicate root of classpath, for example getResource("/file.dat"). If properties file is under the same folder with the class you on which you invoke getResource method, than you should not use '/' prefix.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值