programing tip

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

itbloger 2020. 6. 26. 18:54
반응형

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 ()를 호출하면됩니다. 실제로 Path.Combine을 모방하려는 경우 다음과 같이 작성할 수 있습니다.

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

당신은 할 수 있습니다

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

반응형