ChatGPT解决这个技术问题 Extra ChatGPT

Does Java have a path joining method? [duplicate]

This question already has answers here: Closed 13 years ago.

Exact Duplicate:

combine paths in java

I would like to know if there is such a method in Java. Take this snippet as example :

// this will output a/b
System.out.println(path_join("a","b"));
// a/b 
System.out.println(path_join("a","/b");
See this answer: stackoverflow.com/a/20069477/1151521 it shows the new Java 7 way.

4
4 revs, 3 users 83%

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();
}

Doesn`t work in Java 8. Better option: import java.nio.file.Paths; Path path = Paths.get(mydir, "myfile");
@MarcWittmann, what happens when you do this in Java 8?
The solution is a lot shorter with Java 7's nio: Paths.get(path1, path2)
Just note Path/Paths do not work with jar-s, only with filesystem. See eg. stackoverflow.com/questions/941754/…
D
Dave Jarvis

Try:

String path1 = "path1";
String path2 = "path2";

String joinedPath = new File(path1, path2).toString();

wouldn't getPath() or getAbsolutePath() be better than toString()?
For future reference: toString() is the same as getPath() for the File class.
@fstanis: Still getPath() is more readable compared to toString() (assuming they return the same thing)
S
Soviut

One way is to get system properties that give you the path separator for the operating system, this tutorial explains how. You can then use a standard string join using the file.separator.


T
TofuBeer

This is a start, I don't think it works exactly as you intend, but it at least produces a consistent result.

import java.io.File;

public class Main
{
    public static void main(final String[] argv)
        throws Exception
    {
        System.out.println(pathJoin());
        System.out.println(pathJoin(""));
        System.out.println(pathJoin("a"));
        System.out.println(pathJoin("a", "b"));
        System.out.println(pathJoin("a", "b", "c"));
        System.out.println(pathJoin("a", "b", "", "def"));
    }

    public static String pathJoin(final String ... pathElements)
    {
        final String path;

        if(pathElements == null || pathElements.length == 0)
        {
            path = File.separator;
        }
        else
        {
            final StringBuilder builder;

            builder = new StringBuilder();

            for(final String pathElement : pathElements)
            {
                final String sanitizedPathElement;

                // the "\\" is for Windows... you will need to come up with the 
                // appropriate regex for this to be portable
                sanitizedPathElement = pathElement.replaceAll("\\" + File.separator, "");

                if(sanitizedPathElement.length() > 0)
                {
                    builder.append(sanitizedPathElement);
                    builder.append(File.separator);
                }
            }

            path = builder.toString();
        }

        return (path);
    }
}

Work with the platform. As other answers show Java handles this for users, so there really is no need to roll another.
Because the File constructor is expensive (in terms of time). It interacts with the file system (depends on the implementation). There is no need to write code that is slower on purpose. That being said, the speed should be measured, so it is possible that my code is slower. In addition the answer I provided works for things that are not File based so it is more flexible.
I'm really sorry but speed for something like this is a secondary concern, especially for a site that many people who just want to know how to do the right way are concerned. * Re implements existing Java libraries functionality * Enforces OS specific path conventions (could have been argument inject-able with default at the least) * Question is about path joining, to make it more flexible accept an interface
"I'm really sorry but speed for something like this is a secondary concern, especially for a site that many people who just want to know how to do the right way are concerned" that is why we have accepted answers. There is nothing technically wrong with my answer, it works, it addresses an issue (the speed), and it shows how to do the same sort of thing if it isn't files. You cannot say that speed does not matter for this, what if it is being called millions of times?
" it works, it addresses an issue (the speed)" As you have mentioned above, without benchmarks we don't "know" it's faster. You brought that up, please don't tout speed without some benchmarks if that is the aim. "it shows how to do the same sort of thing if it isn't files." You use File.separator in your example, I don't see how that is portable to a wide range of non file-based systems, could you explain?