programing

Java에는 경로 결합 방식이 있습니까?

prostudy 2022. 9. 6. 21:26
반응형

Java에는 경로 결합 방식이 있습니까?

정확한 복제:

Java로 경로를 결합하다

자바에 그런 방법이 있는지 알고 싶습니다.이 스니펫을 예로 들어 보겠습니다.

// this will output a/b
System.out.println(path_join("a","b"));
// a/b 
System.out.println(path_join("a","/b");

이는 Java 버전7 이전과 관련이 있습니다.

같은 질문에 대한 좋은 답변을 인용하려면:

나중에 문자열로 반환할 경우 getPath()를 호출할 수 있습니다.정말 패스를 흉내내고 싶다면요콤바인은 다음과 같이 쓸 수 있습니다.

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

시험:

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

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

가지 방법은 운영 체제의 경로 구분자를 제공하는 시스템 속성을 가져오는 것입니다. 이 튜토리얼에서는 방법을 설명합니다.그런 다음 표준 문자열 결합을 사용하여file.separator.

이것은 시작입니다. 당신이 의도한 대로 정확히 작동하지는 않지만 적어도 일관된 결과를 만들어 냅니다.

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

언급URL : https://stackoverflow.com/questions/711993/does-java-have-a-path-joining-method

반응형