How to read file from relative path in Java project? java.io.File cannot find the path specified

Viewed 665683

I have a project with 2 packages:

  1. tkorg.idrs.core.searchengines
  2. tkorg.idrs.core.searchengines

In package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code in FileLoader:

File file = new File("properties\\files\\ListStopWords.txt");

But I have this error:

The system cannot find the path specified

Can you give a solution to fix it?

15 Answers

I could have commented but I have less rep for that. Samrat's answer did the job for me. It's better to see the current directory path through the following code.

    File directory = new File("./");
    System.out.println(directory.getAbsolutePath());

I simply used it to rectify an issue I was facing in my project. Be sure to use ./ to back to the parent directory of the current directory.

    ./test/conf/appProperties/keystore 

While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:

URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());

enter image description here

Assuming you want to read from resources directory in FileSystem class.

String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);

System.out.println(Files.readString(path));

Note: Leading . is not needed.

For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem

For me it worked with -

    String token = "";
    File fileName = new File("filename.txt").getAbsoluteFile();
    Scanner inFile = null;
    try {
        inFile = new Scanner(fileName);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    while( inFile.hasNext() )
    {
        String temp = inFile.next( );  
        token = token + temp;
    }
    inFile.close(); 
    
    System.out.println("file contents" +token);

String basePath = new File("myFile.txt").getAbsolutePath(); this basepath you can use as the correct path of your file

if you want to load property file from resources folder which is available inside src folder, use this

String resourceFile = "resources/db.properties";
InputStream resourceStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFile);
Properties p=new Properties();  
p.load(resourceStream);  
      
    System.out.println(p.getProperty("db")); 

db.properties files contains key and value db=sybase

Related