Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading a file from current directory in java

Tags:

java

file

I have a java project where I am reading a file. As the file is in the current directory I am doing this:

String dataset = "./myFile.dat";

But I am getting: java.io.FileNotFoundException saying It can not find the file.

How to fix this? When I give entire path it works...

String dataset = "C:\\eclipse\\workspace\\p1\\src\\myFile.dat";
like image 571
edgarmtze Avatar asked Nov 21 '25 09:11

edgarmtze


1 Answers

If myFile.dat is an application resource, it should be included in a Jar that is on the run-time class-path of the application. Then an URL to the resource can be formed using..

URL urlToData = this.getClass().getResource("path/in/jar/to/myFile.dat");

Don't rely on the user.dir property. Depending on how the app. is started, it might point somewhere very different to the directory of the application or data.

like image 51
Andrew Thompson Avatar answered Nov 22 '25 22:11

Andrew Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!