Java Nio absolute path to relative path - java

I have a path that points to a file on disk, say: C:\folder\dir\dir2\file.txt. In the code, if an exception is thrown when working with this file, it will output the whole path. Ideally, it would be nice not to have the whole directory print out, rather something like ../../dir2/file.txt.
It seems like I should be able to that with the java.nio.file relativize method, I'm just not sure how.
Path file; // C:\folder\dir\di2\file.txt
file.relativize(file.getParent());
I'm approaching this the wrong way I'm sure, just not positive how to accomplish what I'd like.

Get the current working directory
Path pwd = Paths.get("").toAbsolutePath();
and then relativize the target Path
Path relative = pwd.relativize(target);

Related

Is this a relative path or an absolute path?

I'm having a little difficulty determining if the path in the code below is a relative path or an absolute path. Also, in this case, I'm trying to open an image I placed inside a folder called "img" which is inside my java project directory. Please don't mind the double backslash (\), I know these only works on Windows, the only thing I wanted to ask if this path relative or absolute.
ImageView img = new ImageView(new Image("file:img\\square.png"))
As you can find in the documentation here you can pass to the constructor any URL supported by the URL class, which is the case in your example.
If the passed string is not a valid URL, but a path instead, the Image is searched on the classpath in that case.
In your case, it is relative.
The file: URL scheme refers to a file on the client machine. There is no hostname in the file: scheme; you just provide the path of the file. So, the file on your local machine would be file:///~User/2ndFile.html.
Please read this answer for further information.

Java.nio.file.Paths is giving incorrect path for current directory?

I am trying to read the contents of a file using Java.nio.file.Paths class, my code looks like this
package com.test.json;
Path currentDir = Paths.get(".");
System.out.println(currentDir.toAbsolutePath());
It is giving me the path
/home/rohit/workspace/MapReduceExample/.
while the output should be
home/rohit/workspace/MapReduceExample/src/com/test/json/
It is ignoring the component of src folder and packages. Could someone please tell me what I am doing wrong?
I can't give absolute path because I need this code for a map-reduce path, I have to construct path in relative manner. So, my approach is to do
getCurrentDirectoryPath + filename
It appears to me that you are expecting the Path of the directory where your source Java file (that calls Paths.get(".")) resides. But that's not what the path "." will fetch. When a JVM runs your class on the host file system, the value of "." refers to the current working directory of the JVM process. It's very likely that the JVM that runs your class is actually started in that folder: /home/rohit/workspace/MapReduceExample. If you did a
System.out.println(Paths.get(
System.getProperty("user.dir")).toAbsolutePath());
you'll see that it prints the same folder, without the trailing ".".

Why does referencing "src/main/resources" work after compilation, during testing? [duplicate]

I am trying to use a relative path to locate an executable file within a Java class instead of hard-coded lines which worked, but using something like:
final static String directory = "../../../ggla/samples/obj/linux_x86"
fails... what is the proper way of using a relative path in Java?
The most likely explanation is that your current directory is not where you think that it is. You can inspect the system property of user.dir to see what the base path of the application is, or you can do something like this:
System.out.println(new File(".").getCanonicalPath());
right before you use that relative path to debug where your relative reference starts.
Use System.out.println(System.getProperty("user.dir")); to see where your current directory is. You can then use relative paths from this address.
Alternatively if you dont need to update the file you are trying to read obtain it from the classpath using getResourceAsStream("filename");
Karl
What you need is getCanonicalPath or getCanonicalFile to resolve the relative paths.
System.out.println(new File("../../../ggla/samples/obj/linux_x86")
.getCanonicalPath());
You can use relative paths like you describe, and it should work. So the error is probably somewhere else.
Please post a complete program to reproduce your error, then we may be able to help.
I would start by using the separator and path separator specified in the Java File class. However, as I said in my comment, I need more info than "it fails" to be of help.
For relative path, maybe you can use one of the method provide by java for the beginning of the relative path as getRelativePath....
You have to use / and not // in the String in java !

I/O Relative Paths

I'm having a problem with relative paths in my program. The absolute path to the file which I want to use is:
C:\Users\User\Documents\Projects\Project1\src\files\test.txt
Now, I'm unsure of how to make this a relative path, I've tried:
.\files\test.txt
Which throws an error at me, I don't know how to make this go up a folder and read from the test.txt file.
.\files\test.txt is correct, if and only if you run your program from the src directory, and use file IO to read the file, and not resource loading using the class loader.

Java FileOutputStream: path relative to program folder?

What is the best way to find a path relative to the folder where a java application is "installed"?
I have a class with a static method: public static void saveToFile(String fileName)
When I call it with an absolute path, it works, but what I really want is the relative path to where the application is run from, and a folder.
I have not deployed my application, but right now I want to find a path relative to the (Netbeans) project root, and a folder within called data: ProjectName\data\file.dat. Should I use the File class or make it into a URI or something?
Note that I prefer it to be system-independent and will still work if the application is deployed. Eventually the (relative) pathname will be stored in a properties file.
Sorry if this question is a duplicate, any help is appreciated.
What is the best way to find a path relative to the folder where a java application is "installed"?
OS manufacturers have been saying for a long time not to save files in the application directory.
Note that I prefer it to be system-independent and will still work if the application is deployed.
Instead put the File in a sub-directory of user.home. User home is where it should be possible to establish a file object that can be read or written. It is also a place that is reproducible across runs, and platform independent.
If you deploying as a jar, its possible to obtain the jar file name and path the current code is working in like this:
new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
(from How to get the path of a running JAR file?)
Here you go:
String path = System.getProperty("user.dir");
To find relative path to current working directory say new File(".").
If you want to know absolute path of current working directory you can write new File(".").getAbsolutePath() or File(".").getAbsoluteFile()`.
I hope this answers your question. I am sorry if I did not understand you correctly.
To get the absolute path to a file use new File().getCanonicalFile().
new FileOutputStream(new File(".\\target\\dataset.xml").getCanonicalFile())

Categories