Remove filename from a URL/Path in java
Asked Answered
A

9

31

How do I remove the file name from a URL or String?

String os = System.getProperty("os.name").toLowerCase();
        String nativeDir = Game.class.getProtectionDomain().getCodeSource().getLocation().getFile().toString();

        //Remove the <name>.jar from the string
        if(nativeDir.endsWith(".jar"))
            nativeDir = nativeDir.substring(0, nativeDir.lastIndexOf("/"));

        //Load the right native files
        for(File f : (new File(nativeDir + File.separator + "lib" + File.separator + "native")).listFiles()){
            if(f.isDirectory() && os.contains(f.getName().toLowerCase())){
                System.setProperty("org.lwjgl.librarypath", f.getAbsolutePath()); break;
            }
        }

That's what I have right now, and it work. From what I know, because I use "/" it will only work for windows. I want to make it platform independent

Antilles answered 17/2, 2014 at 12:35 Comment(2)
#8075873Mizzle
This / is not windows. ` \ ` is!Gawk
T
26

Consider using org.apache.commons.io.FilenameUtils

You can extract the base path, file name, extensions etc with any flavor of file separator:

String url = "C:\\windows\\system32\\cmd.exe";

String baseUrl = FilenameUtils.getPath(url);
String myFile = FilenameUtils.getBaseName(url)
                + "." + FilenameUtils.getExtension(url);

System.out.println(baseUrl);
System.out.println(myFile);

Gives,

windows\system32\
cmd.exe

With url; String url = "C:/windows/system32/cmd.exe";

It would give;

windows/system32/
cmd.exe
Tommyetommyrot answered 17/2, 2014 at 13:13 Comment(4)
I don't have FilenameUtils I can't import org.apache.commons.io.FilenameUtils.Antilles
@yemto can't import would be "not supposed to" or "don't know what lib has it"?Tommyetommyrot
@PopoFido oh, I don't like to use library's, especially for something that should be this simple.Antilles
What about the drive letter?Gardening
H
23

By utilizing java.nio.file; (afaik introduced after J2SE 1.7) this simply solved my problem:

Path path = Paths.get(fileNameWithFullPath);
String directory = path.getParent().toString();
Hagiography answered 5/1, 2018 at 14:21 Comment(1)
Doesn't work well for HTTP URLs, which wasn't specifically mentioned in the question, but might be of interest to some browsing these answers.Dariusdarjeeling
O
15

You are using File.separator in another line. Why not using it also for your lastIndexOf()?

nativeDir = nativeDir.substring(0, nativeDir.lastIndexOf(File.separator));
Orthodontia answered 17/2, 2014 at 12:45 Comment(5)
Because It returns the wrong thing for my system. But it don't seam to care if it becomes C:\something\something\something/somethingAntilles
The File.separator is returning the file separator dependent to your system. So on Windows you will get "\" while on Unix you get "/". That's why you should use the File.separator.Orthodontia
Game.class.getProtectionDomain().getCodeSource().getLocation().getFile().toString() returns D:/Dropbox/NetBeansProjects/ while System.out.println(File.separator) returns \ so that's wrong. I have windows 7 64bitAntilles
Well if that method always returns "/" you might want to perform a replacement first to ensure the same state in any case. String.replace() might helpOrthodontia
Notice that in order to get the filename, expression should be something like nativeDir.substring(nativeDir.lastIndexOf(File.separator) + 1) (so the substring from the separator, to the end).Badtempered
M
9
File file = new File(path);
String pathWithoutFileName = file.getParent();

where path could be "C:\Users\userName\Desktop\file.txt"

Missy answered 9/8, 2020 at 15:20 Comment(0)
D
3

The standard library can handle this as of Java 7

Path pathOnly;

if (file.getNameCount() > 0) {
  pathOnly = file.subpath(0, file.getNameCount() - 1);
} else {
  pathOnly = file;
}

fileFunction.accept(pathOnly, file.getFileName());
Dispread answered 14/3, 2017 at 3:27 Comment(1)
path.getNameCount() documentation says: "the number of elements in the path, or 0 if this path only represents a root component" This could cause issues...Hypnotism
A
1

Kotlin solution:

val file = File( "/folder1/folder2/folder3/readme.txt")
val pathOnly = file.absolutePath.substringBeforeLast( File.separator )
println( pathOnly )

produces this result:

/folder1/folder2/folder3

Akerley answered 16/5, 2021 at 5:42 Comment(0)
D
0

Instead of "/", use File.separator. It is either / or \, depending on the platform. If this is not solving your issue, then use FileSystem.getSeparator(): you can pass different filesystems, instead of the default.

Divestiture answered 17/2, 2014 at 12:36 Comment(3)
I would. But File.separator return a "\" while nativeDir uses "/"Antilles
Then shouldn't something like this work? if(nativeDir.endsWith(".jar")){ int index = Math.max(nativeDir.lastIndexOf("/"), nativeDir.lastIndexOf("\\")); nativeDir = nativeDir.substring(0, index); }Antilles
Added more info. That should resolve the difference with native dir.Divestiture
E
0

I solve this problem using regex.

For windows:

String path = "";
String filename = "d:\\folder1\\subfolder11\\file.ext";
String regEx4Win = "\\\\(?=[^\\\\]+$)";
String[] tokens = filename.split(regEx4Win);
if (tokens.length > 0)
   path = tokens[0]; // path -> d:\folder1\subfolder11
Earful answered 3/3, 2017 at 11:10 Comment(0)
C
-1

Please try below code:

file.getPath().replace(file.getName(), "");
Couvade answered 9/7, 2020 at 14:37 Comment(1)
Breaks if any directory has the same name as the target file. Since files without an extension are fine from an OS point of view, this may lead to something like: C:\A\B\C\B being changed to C:\A\\C, so you have unintentionally lost a directory.Noodlehead

© 2022 - 2024 — McMap. All rights reserved.