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

JavaFile

Java Problem Overview


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 have this error:

The system cannot find the path specified

Can you give a solution to fix it? Thanks.

Java Solutions


Solution 1 - Java

If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.

Assuming that ListStopWords.txt is in the same package as your FileLoader class, then do:

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

Or if all you're ultimately after is actually an InputStream of it:

InputStream input = getClass().getResourceAsStream("ListStopWords.txt");

This is certainly preferred over creating a new File() because the url may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File constructor.

If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed the InputStream immediately to the load() method.

Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));

Note: when you're trying to access it from inside static context, then use FileLoader.class (or whatever YourClass.class) instead of getClass() in above examples.

Solution 2 - Java

The relative path works in Java using the . specifier.

  • . means same folder as the currently running context.
  • .. means the parent folder of the currently running context.

So the question is how do you know the path where the Java is currently looking?

Do a small experiment

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

Observe the output, you will come to know the current directory where Java is looking. From there, simply use the ./ specifier to locate your file.

For example if the output is

> G:\JAVA8Ws\MyProject\content.

and your file is present in the folder "MyProject" simply use

File resourceFile = new File("../myFile.txt");

Hope this helps.

Solution 3 - Java

The following line can be used if we want to specify the relative path of the file.

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

Solution 4 - Java

InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
	BufferedReader reader = new BufferedReader(new InputStreamReader(in));
	String line = null;
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
		}
} catch (Exception e) {
	e.printStackTrace();
}

Solution 5 - Java

try .\properties\files\ListStopWords.txt

Solution 6 - Java

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 

Solution 7 - Java

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

Solution 8 - Java

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.

Solution 9 - Java

I wanted to parse 'command.json' inside src/main//js/Simulator.java. For that I copied json file in src folder and gave the absolute path like this :

Object obj  = parser.parse(new FileReader("./src/command.json"));

Solution 10 - Java

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

Solution 11 - Java

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

Solution 12 - Java

If you are trying to call getClass() from Static method or static block, the you can do the following way.

You can call getClass() on the Properties object you are loading into.

    public static Properties pathProperties = null;
    
    static { 
        pathProperties = new Properties();
        String pathPropertiesFile = "/file.xml";
//      Now go for getClass() method
        InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
    }

Solution 13 - Java

If text file is not being read, try using a more closer absolute path (if you wish you could use complete absolute path,) like this:

FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");

assume that the absolute path is:

C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt

Solution 14 - Java

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

Solution 15 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontiendvView Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavaSamratView Answer on Stackoverflow
Solution 3 - JavasanthoshView Answer on Stackoverflow
Solution 4 - JavafrictionlesspulleyView Answer on Stackoverflow
Solution 5 - JavabUg.View Answer on Stackoverflow
Solution 6 - JavaabdevView Answer on Stackoverflow
Solution 7 - JavaiamallamaView Answer on Stackoverflow
Solution 8 - JavaR SunView Answer on Stackoverflow
Solution 9 - JavasverView Answer on Stackoverflow
Solution 10 - JavaJ.LuanView Answer on Stackoverflow
Solution 11 - JavaCheckView Answer on Stackoverflow
Solution 12 - Javaarun_kkView Answer on Stackoverflow
Solution 13 - JavaKR NView Answer on Stackoverflow
Solution 14 - Javauser13499397View Answer on Stackoverflow
Solution 15 - JavaSundararajan SView Answer on Stackoverflow