Search code examples
javaeclipsefilepathworkspace

Resolving File paths - 'File not found' error in Eclipse


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");

Solution

  • 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());