How to get absolute path of directory of a file? - java

How can I get an absolute path of a directory containing a file specified:
// current dir is "/home/me/dev"
File file = new File("./target/test.txt");
assert absolute(file).equals("/home/me/dev/target");
It's Java 6.

You mean the methods in the documentation?
File file = new File("./target/test.txt");
String dirPath = file.getAbsoluteFile().getParentFile().getAbsolutePath()
assert dirPath.equals("/home/me/dev/target");

assert file.getParentFile().getAbsolutePath().equals("/home/me/dev/target");

Related

After created a file it got extra './ ' on path

I created an empty File and store the extracted value/content from a jar. The jar is running on linux.
String filename ="base_script";
File targetFile = new File( filename + ".sh");
String pathStr=null;
//empty file
targetFile.createNewFile();
if(targetFile.exists()) {
InputStream link = (getClass().getResourceAsStream(this.userScriptPath));
Files.copy(link,
targetFile.getAbsoluteFile().toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
pathStr = targetFile.getAbsolutePath();
}
This is the file path ./base_script.sh
And this is file absolute path apps/MyApps/./base_script.sh
My question is why there's an extra ./ on the absolute path?
It's not clear why you have "./" in the name as you define the value without it. Anyway this will resolve the path to the real name without any "./" or ".." in a path:
pathStr = targetFile.toPath().toRealPath().toString()

How to get path to package in Eclipse (Java)

I'm currently reading a txt file in Java, which is located in a package with the scanner object.
To receive the file location I use a quick and dirty method:
File currentDirectory = new File(new File(".").getAbsolutePath());
String location = currentDirectory.getAbsolutePath().replace(".", "")+"\\corefiles\\src\\filereadingexample\\";
Is there a better way of doing so?
I'd love to improve my code.
Greetings
J
Use a URL
URL resource = getClass().getResource("/path/to/text/file.txt");
As the path, since your text file is inside a package, use the package structure. For example, assume your file(myfile.txt) is inside
com.myproject.files
package, your path should be
"/com/myproject/files/myfile.txt"
(mind the leading slash. It's necessary)
Now you can create a File using the URL
new File(resource.getFile());
The "resource.getFile()" returns the absolute path to the file also.
Hope this helps
Get current diretory path
String currentDirPath = System.getProperty("user.dir");
String ohterPackages = currentDirPath + File.separator + "filereadingexample\\fileName.txt";
User home directory
String homePath = System.getProperty("user.home");

How to shorten file path (get canonical path) in java?

Is there any way in java which can shorten absolute path to directory.
For example:
./data/../system/bin/ => ./system/bin/
Yes, use http://docs.oracle.com/javase/7/docs/api/java/io/File.html#getCanonicalPath().
File file = new File("C:/Users/../Users");
System.out.println(file.getAbsolutePath()); // C:\Users\..\Users
System.out.println(file.getCanonicalPath()); // C:\Users

Jump one folder up in a URL in Java

I have a URL that I get as below:
String jarFilePath = getClass().getProtectionDomain().getCodeSource().getLocation()
This would get me the complete path to the jar file. Now how do I jump one folder up and append some other path to it? For example., if the jarFilePath is something like:
c:/path/to/jar/file.jar
I want to jump one folder up and append another relative path like below:
c:/path/to/resources/path/to/resources/
Where the folders resources and jar are at the same directory level in the file system.
File f = new File("C:/path/to/jar/file.jar");
File dest = new File(f.getParentFile().getParentFile(), "resources/path/to/resources");
Just use the File-Object, that makes a lot of things easier:
import java.io.File;
String pathname = "c:/path/to/jar/file.jar";
File f = new File(pathname);
String p = f.getParent();
Try and use a File object:
File jarFile = new File(jarFilePath);
File newFolder = new File( jarFile.getParentFile().getParentFile(), "resources/path/to/resources");
If you want to use the path as a string, try using Apache Commons IO's FilenameUtils:
String resourcesPath = FilenameUtils.normalize( FilenameUtils.getPath(jarFilePath) + "/../resources/path/to/resources");
You have several ways.
You can split the path into it's elements and rebuild it until array.length -3 (-1 would be filename, -2 the last folder)
You could simple remove the file and append another ../ (which just means: "Go one directory back") (that would be something like this then: c:/path/to/jar/../resources/path/to/resources/)
You gould use a regex to get rid of the last folder and file. something like /[^/]+/[^/]+$

Get the filePath from Filename using Java

Is there a easy way to get the filePath provided I know the Filename?
You can use the Path api:
Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
Look at the methods in the java.io.File class:
File file = new File("yourfileName");
String path = file.getAbsolutePath();
I'm not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:
System.out.println("File path: " + new File("Your file name").getAbsolutePath());
The File class has several more methods you might find useful.
Correct solution with "File" class to get the directory - the "path" of the file:
String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();
which will return:
path = "C:\\Temp\\your directory"
You may use:
FileSystems.getDefault().getPath(new String()).toAbsolutePath();
or
FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()
This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.
Example: /src/main/java...

Categories