How to Read File from Relative Path in Java Project? Java.Io.File Cannot Find the Path Specified

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

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.

How does Java resolve a relative path in new File()?

There is a concept of a working directory.

This directory is represented by a . (dot).

In relative paths, everything else is relative to it.

Simply put the . (the working directory) is where you run your program.

In some cases the working directory can be changed but in general this is

what the dot represents. I think this is C:\JavaForTesters\ in your case.

So test\..\test.txt means: the sub-directory test

in my working directory, then one level up, then the

file test.txt. This is basically the same as just test.txt.

For more details check here.

http://docs.oracle.com/javase/7/docs/api/java/io/File.html

http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

Reading XML from relative path - java.io.FileNotFoundException:(The system cannot find the path specified)

For java unit tests such as this, my recommendations for test files are:

  1. Test resources go under src/test/resources, and then in a folder to match the package of the test class.
  2. Use IOUtils.toString(InputStream) from commons-io to read in the file.
  3. Use Class.getResourcesAsStream(String) to reference the file itself.

Thus for com.my.package.MyTest, I would save the XML file as src/test/resources/com/my/package/test_document1.xml, and the code might look like:

try(InputStream in = MyTest.class.getResourceAsStream("test_document1.xml")) {
return IOUtils.toString(in);
}

Java- relative path of text file in main?

If you are using eclipse, place your text file in the root of the project folder, outside the /src and /bin folders. It should be now accessible via a relative path directly.

If you want to access a file in src folder, you have to append the /src/ prefix before the file path/name

Get file from relative path in windows

Here is an other solution, how to get the directory, the application was started in:

String current_dir = System.getProperty("user.dir");

After this the absolute path to the .doc can be built using the current working directory:

Paths.get(current_dir, "test/java/com/pro/mockfiles/My-DOC-FILE.doc");

with Paths.get(...)

The system cannot find the file specified in java

I have copied your code and it runs fine.

I suspect you are simply having some problem in the actual file name of hello.txt, or you are running in a wrong directory. Consider verifying by the method suggested by @Eng.Fouad

Cannot Find Path Specified Creating File Despite Existing Parent Directory

The issue is that zip files can have trailing spaces in their paths. For example, "Test whatever .zip" could be the file name so java sees the folder as "/Test whatever /" and it tries to create that folder. Windows tells java that it succeeded, but really it created a folder at "/Test Whatever/". When dealing with folders, the file IO has no issue with this, but when writing files, it completely bombs as it's looking for the path explicitly. It does not truncate the extra white space the same way it does when dealing with folders, as you would expect.

Here is the code I used to resolve it:

String path = (outputFolder + File.separator + fileName).replace(" ", "");

File newFile = new File(path);

how to read text file relative path

This is a valid absolute path (on the systems I'm aware of):

    /path/to/directory/../../otherfolder/etc/

So what the other answer was saying, was to get the path to the current directory with:

    String filePath = new File("").getAbsolutePath();

Then concatenate your relative path with:

    filePath.concat("path to the property file");

.exist() - file does not exist, when using relative path

An absolute path starts from the filesystem root. Compare it to an address on a letter. The postman knows where to deliver that letter.

A relative path is not a target address. It is more like - when you see the gas station, turn left. Depending from which direction you come, you end up in various other locations.

Back to computers: relative paths are calculated based on a current working directory. You can print that from your java program by checking

How to get the current working directory in Java?

I usually write my code to be a bit clearer about the events. The following code will not only tell whether it found the file but also let you know where exactly it was searching for it.

        // File object
File myFile = new File("text1.txt");

// Prints a String, that tells you if the file exists
System.out.println("File "+myFile.getAbsolutePath()+" exists = " + myFile.exists());


Related Topics



Leave a reply



Submit