How to Combine Paths in Java

Joining paths in Java

Even though the original solution for getting the current directory using the empty String works. But is recommended to use the user.dir property for current directory and user.home for home directory.

Path currentPath = Paths.get(System.getProperty("user.dir"));
Path filePath = Paths.get(currentPath.toString(), "data", "foo.txt");
System.out.println(filePath.toString());

output:

/Users/user/coding/data/foo.txt

From Java Path class Documentation:

A Path is considered to be an empty path if it consists solely of one name element that is empty. Accessing a file using an empty path is equivalent to accessing the default directory of the file system.


Why Paths.get("").toAbsolutePath() works

When an empty string is passed to the Paths.get(""), the returned Path object contains empty path. But when we call Path.toAbsolutePath(), it checks whether path length is greater than zero, otherwise it uses user.dir system property and return the current path.

Here is the code for Unix file system implementation: UnixPath.toAbsolutePath()


Basically you need to create the Path instance again once you resolve the current directory path.

Also I would suggest using File.separatorChar for platform independent code.

Path currentRelativePath = Paths.get("");
Path currentDir = currentRelativePath.toAbsolutePath(); // <-- Get the Path and use resolve on it.
String filename = "data" + File.separatorChar + "foo.txt";
Path filepath = currentDir.resolve(filename);

// "data/foo.txt"
System.out.println(filepath);

Output:

/Users/user/coding/data/foo.txt

Does Java have a path joining method?

This concerns Java versions 7 and earlier.

To quote a good answer to the same question:

If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:

public static String combine (String path1, String path2) {
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}

Combine two strings to a single string representing a path

FilenameUtils.normalize() from Apache Commons IO does what you want.

example:

FilenameUtils.normalize("foo/" + "/bar");

returns the string "foo/bar"

Add a file name to a Path object

You are looking for Path.resolve():

Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the resolve method. For example, suppose that the name separator is "/" and a path represents "foo/bar", then invoking this method with the path string "gus" will result in the Path "foo/bar/gus".

So you should use this:

Path pathToFolder = Path.of("/Users/someuser/");
Path pathToFile = pathToFolder.resolve("your-file-name");
BufferedWriter writer = Files.newBufferedWriter(pathToFile);

How to safely combine strings into file path and open filewriter?

Use Files.newBufferedWriter(Path, OpenOption...).

try (Writer myWriter = Files.newBufferedWriter(Paths.get(folder, fileName))) {
// other code
}

Note that, while the FileWriter constructor uses the JVM's default encoding, this method uses the UTF-8 encoding, which is considered generally more useful. If you need to replicate the behavior of the FileWriter constructor, use

Files.newBufferedWriter(path, Charset.defaultCharset());

Failing 8/10 test cases while joining 2 portions of a path

How about this:

static String joinPath(String path1, String path2)
{
return String.format("%s/%s", path1, path2).replaceAll("/+", "/");
}

We insert a "/" between whatever paths we're given, then collapse strings of one or more "/"s to a single "/".

Test:

portion1 portion2 : portion1/portion2
portion1/ portion2 : portion1/portion2
portion1 /portion2 : portion1/portion2
portion1/ /portion2 : portion1/portion2

Adding an infix between file name and extension using java 8

How about this? you can use Path#resolveSibling(String) to get the path relative to the original path. and use the Path#getFileName to get the filename in path.

thanks to @Holger point out that I can use the regex "(.*?)(\\.[^.]+)?$" instead.

public Path resize(Path original) {
return original.resolveSibling(original.getFileName().toString()
// v--- baseName
.replaceFirst("(.*?)(\\.[^.]+)?$", "$1_resized$2"));
// ^--- extension
}

Output

//            v---for printing, I used the `String` here,actually is Paths.get(...)
resize("/a/b/image.jpg") => "/a/b/image_resized.jpg";

resize("/a/b/image.1.jpg") => "/a/b/image.1_resized.jpg";

resize("/a/b/image1") => "/a/b/image1_resized";


Related Topics



Leave a reply



Submit