Get path of file without drive letter - Windows 10 / Java 8 - java

Windows 10
Java 8
When I call getCanonicalPath on a File object, I get a string like this
C:\data\processed\Test.xml
How do I get the same string but without C:\ and if possible also with / instead of \?

You can use NIO.2 API and its objects Path and Paths which is a abstraction over a file system.
Path path = Paths.get("C:\\data\\processed\\Test.xml");
You can also get Path from File using File::toPath. Actually, you need to get all the names in the path:
File file = new File("C:\\data\\processed\\Test.xml");
Path path = file.toPath();
int count = path.getNameCount(); // the count of names
path = path.subpath(0, count); // all the names
Alternatively (thanks to #Holger) using Path:relativize (you find a relative path to the root C:/ which is all the names.
File file = new File("C:\\data\\processed\\Test.xml");
Path path = file.toPath();
path = path.getRoot().relativize(path);
Here are some relevant methods:
path.getRoot() returns C:\
path.getNameCount() returns the number of name elements in the path (3 in this case)
path.getName(0) returns data, path.getName(1) returns processed etc...
path.subpath(fromInclusive, toExclusive) returns a relative Path that is a subsequence of the name elements of this path.
path.relativize(path) returns a relative path to a parameter.
The object Path represents an abstraction of the actual path. If you want to replace \ with / as a String, you might need to use String::replace.
String stringPath = path.toString().replace('\\', '/');
System.out.println(path); // data\processed\Test.xml
System.out.println(stringPath); // data/processed/Test.xml

Here is a short answer:
File file = new File("c:\\tmp\\abc.txt"); //file =C:\tmp\abc.txt
String filePath= file.getCanonicalPath(); //path= C:\tmp\abc.txt
String str=filePath.replace('\\', '/'); //str= C:/tmp/abc.txt
java.net.URI uri= new java.net.URI(str); //uri= C:/tmp/abc.txt
uri.getPath(); //uri.getPath() = /tmp/abc.txt

Related

Relative path to database file in Java

I have to access a database file in my Java project but I can't get the path right.
The full path is C:\Hogwarts\db\hogdb.fdb.
I tried to use this code line to find the the current relative path:
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);
and it says the current relative path is: C:\Hogwarts.
Right now my code looks like this :
minDataBas = new InfDB("db\\HOGDB.FDB");
new HuvudFonster(minDataBas).setVisible(true);
What am I missing?
In fact all elements are there; just use an absolute path.
String cwd = System.getProperty("user.dir"); // Alternative
Path cwdPath = Paths.get(cwd);
Path dbPath = Paths.get(cwd, "db/hogdb.fdb");
String db = dbPath.toAbsolutePath().toString();
if (!Files.exists(dbPath)) {
throw new IllegalStateException("Wrong path for database: " + db);
}
minDataBas = new InfDB(db);
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.
I think instead it should be
minDataBas = new InfDB("C:\\Hogwarts\\db\\HOGDB.FDB");

list the filenames without showing the parent path

I am listing all the files names in a given directory( recursively). That includes showing the file names in sub-directories also.
File file = new File(FILE_PATH);
// Recursively search for all the resource files.
Collection files = FileUtils.listFiles(file, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
for (Iterator iterator = files.iterator(); iterator.hasNext();)
{
File fileIter = (File) iterator.next();
System.out.println("File = " + fileIter.getPath());
}
Where File is the parent directory ("C:\Users\sd\Desktop\sdsd)
Now the code above works file and list me all the files in the that directory and sub directory, like
C:\Users\sd\Desktop\sdsd\TagCategory\healthoutcomes_queries\Neurological.txt
but I want to show only (the path inside of the parent path)
TagCategory\healthoutcomes_queries\Neurological.txt
How can I do that.
Use Path.relativize()
Constructs a relative path between this path and a given path.
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".
So you just need to create a relative path from the parent path by invoking parentPath.relativize(filePath) and do it for each file :
Path parentPath = Paths.get(FILE_PATH);
for (Iterator<File> iterator = files.iterator(); iterator.hasNext();){
Path filePath = iterator.next().toPath();
Path relativePath = parentPath.relativize(filePath);
System.out.println("File = " + relativePath );
}
Note that you should use a generic collection to avoid casts : Collection<File>, and the modern idiom for looping through iterators using the "enhanced for loop" is cleaner to read:
for (File file : files) {
System.out.println("File = " +
parentPath.relativize(file.toPath()));
}
Just add substring:
fileIter.getPath().substring(file.length())
You can use the substring command to get that value as per the below..
If that parent directory is going to remain the same length then it would simply be
fileIter.getPath().substring(25);
This will get all of the characters after the 25th character in the string, if you wanted to omit the .txt for example you can specify where the substring will end, the below takes three off the total length.
fileIter.getPath().substring(25, fileIter.getPath().length() - 3);
For more details on the substring method see https://beginnersbook.com/2013/12/java-string-substring-method-example/
What's the point of complicating your code by using old third-party libraries? Just use plain Java: it does exactly the same thing as your multi-line method:
Path root = Paths.get(FILE_PATH);
Files.walk(root).forEach(path -> System.out.println("File = " + root.relativize(path)));

Java.io.file constructor to deal with UNC file path

When I try to use the JAR file in the UNC path, I find I met a problem. The constructor of java.io.file will always convert a UNC file path to local path.
For example, I try
String dirStr = "file:\\\\dir1\dir2\file.jar!Myclass";
File ff = new File(dirStr);
System.out.println(ff.toString());
I'll get output like: file:\dir1\dir2\file.jar!Myclass. But what I expect to get is file:\\dir1\dir2\file.jar!MyClass.
I tried to add more slashes in the dirStr, but it can't work. Because in the java.io.file, it'll call method to remove duplicated slashes.
And I try to use the URI to create the ff. But the output will be \dir1\dir2\file.jar!Myclass, which is not available to use JAR file successfully. I think the form of JAR must be start with the file: protocol to use parse the string ending with ! in above string \dir1\dir2\file.jar!Myclass.
Is there any way can new File() to get the pathname of File, i.e. ff, like file:\\dir1\dir2\file.jar!MyClass.
Since your input dir String is UNC type, i think you should use Java's URI.
Example code:
URI uri = new URI(dirStr);
System.out.println(uri.toString()); // If you want to get the path as URI
File ff = new File(uri.getPath()); // If you want to access the file.
The other better way is using Path:
URI uri = new URI(dirStr);
Path path = Paths.get(uri); // Or directly Path path = Paths.get(dirStr);
File ff = path.toFile(); // << your file here
path.toUri(); // << your uri path here
The constructor File(String) takes a path, not a URL. Remove the file: part and use two backslashes for every one in the actual filename, to satisfy the compiler's escaping rules. Or use the correct number of forward slashes.

Create directory at given path in Java - Path with space

I have my java code like below-
string folderName = "d:\my folder path\ActualFolderName";
File folder = new File( folderName );
folder.mkdirs();
So here as given directory path has space in it. folder created is d:\my, not the one I am expecting.
Is there any special way to handle space in file/folder paths.
You should us \\ for path in java. Try this code
String folderName = "D:\\my folder path\\ActualFolderName";
File folder = new File( folderName );
folder.mkdirs();
Or use front-slashes / so your application will be OS independent.
String folderName = "D:/my folder path1/ActualFolderName";
Unless you are running a really old version of Java, use the Path API from JDK7:
Path p = Paths.get("d:", "my folder path", "ActualFolderName");
File f = p.toFile();
It will take care of file separators and spaces for you automatically, regardless of OS.
Following alternatives should work in Windows:
String folderName = "d:\\my\\ folder\\ path\\ActualFolderName";
String folderName = "\"d:\\my folder path\\ActualFolderName\"";
You need to escape your path (use \\ in your path instead of \) and you also need to use String, with an uppercase S, as the code you posted does not compile. Try this instead, which should work:
String folderName = "D:\\my folder path\\ActualFolderName";
new File(folderName).mkdirs();
If you are getting your folder name from user input (ie.not hardcoded in your code), you don't need to escape, but you should ensure that it is really what you expect it is (print it out in your code before creating the File to verify).
If your are still having problems, you might want to try using the system file separator character, which you can get with System.getProperty(file.separator) or accesing the equivalent field in the File class. Also check this question.
You need to escape path seprator:
String folderName = "D:\\my folder path\\ActualFolderName";
File file = new File(folderName);
if (!file.exists()) {
file.mkdirs();
}
First of all, the String path you have is incorrect anyway as the backslash must be escaped with another backslash, otherwise \m is interpreted as a special character.
How about using a file URI?
String folderName = "d:\\my folder path\\ActualFolderName";
URI folderUri = new URI("file:///" + folderName.replaceAll(" ", "%20"));
File folder = new File(folderUri);
folder.mkdirs();

Get path directory only and discard file in Java

How do we actually discard last file from java string and just get the file path directory?
Random Path input by user:
C:/my folder/tree/apple.exe
Desired output:
C:/my folder/tree/
closest solution i found is from here . The answer from this forum only display last string acquired not the rest of it. I want to display the rest of the string.
The easiest and most failsafe (read: cross-platform) solution is to create a File object from the path.
Like this:
File myFile = new File( "C:/my folder/tree/apple.exe" );
// Now get the path
String myDir = myFile.getParent();
Try that:
String path = "C:/my folder/tree/apple.exe";
path = path.substring(0, path.lastIndexOf("/")+1);

Categories