How to Define a Relative Path in Java

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.

Java using relative path instead of absolute path

Java does relative paths just fine. Clearly, then, the 'current working directory' for your java process is not the same as the cwd when you're invoking nano.

You can check the CWD in java. Either way will work:

System.out.println(new File(".").getAbsolutePath());

or:

System.out.println(System.getProperty("user.dir"));

You should find that it is different. The 'cwd' for a java process is the cwd that it was set to by whatever started java. If you're invoking java from the command line, it'll be the directory you're in as you do so. If you are double clicking a jar, it'll be the directory the jar is in. If you're making a windows shortcut, it's the directory listed in the shortcut. Example:

cd /foo/bar
java -jar /bar/baz/hello.jar

In the above example, the cwd is /foo/bar. Not /bar/baz.

How to create the relative path in Java?

Relativize!

There is Path relativize(Path other)

Relativization is the inverse of resolution. This method attempts to
construct a relative path that when resolved against this path, yields
a path that locates the same file as the given path. For example, on
UNIX, if this path is "/a/b" and the given path is "/a/b/c/d" then the
resulting relative path would be "c/d". Where this path and the given
path do not have a root component, then a relative path can be
constructed. A relative path cannot be constructed if only one of the
paths have a root component. Where both paths have a root component
then it is implementation dependent if a relative path can be
constructed. If this path and the given path are equal then an empty
path is returned.

For any two normalized paths p and q, where q does not have a root
component,

p.relativize(p .resolve(q)).equals(q) When symbolic links are
supported, then whether the resulting path, when resolved against this
path, yields a path that can be used to locate the same file as other
is implementation dependent. For example, if this path is "/a/b" and
the given path is "/a/x" then the resulting relative path may be
"../x". If "b" is a symbolic link then is implementation dependent if
"a/b/../x" would locate the same file as "/a/x".

Example

Path dir = Path.of("/var/lib");
Path file = Path.of("/var/lib/someapp/1.txt");
Path relative = dir.relativize(file);
System.out.print(relative);

Output

someapp/1.txt

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

How I can write a file using relative path in Java

You should do something like this:

Path relativePath = Paths.get("<put your path here>");
Path absolutePath = relativePath.toAbsolutePath();
System.out.println("Current relative path is: " + absolutePath.toString());

Another option could be:

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

This gives you the current working dir, so then work you path from it.

EDIT

For what you say in the comment:
There is no problem in using relative paths,
Your problem then could be one of these alternatives:

  • The base path is not the one you think

    The same lines I put above should help you debug the problem, using them you could see what absolute path you get, for sure it won't be the one you think it is.

  • The problem is the ".", I have not tested it but maybe this could give you some kind of problem under windows.

  • The src directory does not exist, maybe it takes us to the first point or maybe (depending on your application) it was not created/installed...

But, even you you want to work with relative paths, at some point (even if you do not do it explicitly), they get converted to absolute paths, so it would do no harm to you to convert them to absolute paths just before using them, at least when debugging or while you get some confidence working with paths.

How define relative path to file?

I do not pretend to be correct, but it worked:

  1. I created the folder resources in src -> main and moved the folder config there. I created the folder resources in src -> test and moved the all other folders there. The result is such a structure:
src
|----main
| |
| |----java
| |----resources
| | |----config
| | | |----application.properties
|
|----test
| |----resources
| | |----features
| | |----pipes
| | |----testdata
| | |----webdrivers

  1. Instead System.setProperty("TagConfigFile", "../../config/application.properties");
    I wrote System.setProperty("TagConfigFile", "./config/application.properties"); in RunnerTest.java class

If someone offers a more beautiful working solution, I will be very glad

Relative path to database file in Java

From the InfDB.java file:

@param path Path to the Firebird DB, for example C:/DB.FDB or for Mac /User/DB.FDB

Providing the absolute path, as opposed to relying on the method inferring you are using a relative path, should resolve the issue. Hence, use:

minDataBas = new InfDB("C:\\Hogwarts\\db\\HOGDB.FDB");

or if you know that the database file will be similarly relative to the current working directory for wherever it has launched, you could use the previously found working directory path and append the remaining location as such

Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
minDataBas = new InfDB(s + "\\db\\HOGDB.FDB");

If you cannot be sure where the file will there are a variety of techniques you could use to have the user define where the file is. Setting a path variable, configuration files or simply taking user input.



Related Topics



Leave a reply



Submit