Question

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");
Was it helpful?

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top