0

My current directory has files registers.xml and MySaxparser.java. But I still get a File not found error when i use new File("register.xml");

My cwd is : C:\Users\nb\workspaceAndroid\MySaxParser

Im using Java 1.7 , Eclipse platform on windows

  public static void main(String[] args) {
        File file1 = new File("register.xml");
          if(file1.exists()){
              System.out.println("File existed");
          }else{
              System.out.println("File not found!");
          }
   System.out.println("Working Directory = " +  System.getProperty("user.dir"));

Output:

File not found!
Working Directory = C:\Users\nb\workspaceAndroid\MySaxParser

I tried the line below whcih didnt work too.

File file1 = new File("C:\\Users\\nb\\workspaceAndroid\\MySaxParser\\register.xml");
Nikhil
  • 797
  • 6
  • 12
  • 30

2 Answers2

3

The current working directory in Eclipse Java project is different from the directory where the files are kept

directory C:\Users\nb\workspaceAndroid\MySaxParser\src

Working dir : C:\Users\nb\workspaceAndroid\MySaxParser

Make sure the file paths are relative to the working directory.

Nikhil
  • 797
  • 6
  • 12
  • 30
3

Use getClass().getResource() to read a file in the classpath:

URL url = getClass().getResource("register.xml");

Complete code:

URL url = getClass().getResource("register.xml");
File file = new File(url.toURI());
Sunil Manheri
  • 2,313
  • 2
  • 18
  • 19
  • this anwser didn't work for me because you cannot call getClass from static class. In case you are working on a static class, e.g. public static main, use the [Name_of_your_Class].class.getResource(...) instead: e.g. MySaxParser.class.getResource("register.xml") for further details see answer: https://stackoverflow.com/a/17397548/1806436 – George_DLJ Jun 19 '19 at 12:48