3

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";
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
edgarmtze
  • 24,683
  • 80
  • 235
  • 386

2 Answers2

1

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0

Try this:

String dataset = System.getProperty("user.dir") + "/myFile.dat"; 
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • This is a fragile approach. See my answer, as well as the thread linked by @talnicolas for more details. – Andrew Thompson Jul 28 '11 at 04:05
  • -1 At first I did not notice the `/` before the file name. That is even *more* fragile. The `File(File, String)` constructor will account for different separators on different platforms. For constructing `String` representations of file objects (something I do not recommend), use `System.getProperty("file.separator")`. – Andrew Thompson Jul 28 '11 at 07:06