5

I've a .txt file ("file.txt") in my netbeans "/build/classes" directory.

In the same directory there is the .class file compiled for the following code:

try {
File f = new File("file.txt");
Scanner sc = new Scanner(f);
}
catch (IOException e) {
   System.out.println(e);
}

Debugging the code (breakpoint in "Scanner sc ..") an exception is launched and the following is printed:

java.io.FileNotFoundException: file.txt (the system can't find the specified file)

I also tried using "/file.txt" and "//file.txt" but same result.

Thank you in advance for any hint

dragonmnl
  • 14,578
  • 33
  • 84
  • 129
  • 1
    I think your question is fully answered by the accepted answer of this question: http://stackoverflow.com/questions/1480398/java-reading-a-file-from-current-directory –  May 31 '12 at 09:05
  • In addition to Hassan's comment, I always include f.getAbsolutePath() in my error messages about files so that I know what file I'm talking about. – Thom May 31 '12 at 09:13

5 Answers5

7

If you just use new File("pathtofile") that path is relative to your current working directory, which is not at all necessarily where your class files are.

If you are sure that the file is somewhere on your classpath, you could use the following pattern instead:

URL path = ClassLoader.getSystemResource("file.txt");
if(path==null) {
     //The file was not found, insert error handling here
}
File f = new File(path.toURI());
Joel Westberg
  • 2,656
  • 1
  • 21
  • 27
2

The JVM will look for the file in the current working directory.

Where this is depends on your IDE settings (how your program is executed).

To figure out where it expects file.txt to be located, you could do

System.out.println(new File("."));

If it for instance outputs

/some/path/project/build

you should place file.txt in the build directory (or specify the proper path relative to the build directory).

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • thank you. Now I try. But a question: If I compile the code with Netbeans (for example) and then one person execute it in windows command line in another computer will it works correctly or may give the same problem? – dragonmnl May 31 '12 at 09:09
  • It will work fine as long as you provide the the file-path relative to the current working directory (and as long as the windows user launches the program from the same path). – aioobe May 31 '12 at 09:12
1

Try:

File f = new File("./build/classes/file.txt");
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
0
Use "." to denote the current directory

String path = "./build/classes/file.txt";

File f = new File(path);
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
0

File Object loads, looking for match in its current directory.... which is Directly in Your project folder where your class files are loaded not in your source ..... put the file directly in the project folder