반응형
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
반응형
'programing tip' 카테고리의 다른 글
URL과 파일 이름을 안전하게하기 위해 문자열을 삭제 하시겠습니까? (0) | 2020.06.26 |
---|---|
CSV에서 큰 따옴표를 올바르게 이스케이프 처리 (0) | 2020.06.26 |
Node.js에서 cURL이 동일합니까? (0) | 2020.06.26 |
팬더는 각 그룹 내에서 최고 n 개의 레코드를 얻습니다. (0) | 2020.06.26 |
커밋, 커밋 및 푸시, 커밋 및 동기화의 차이점 (0) | 2020.06.26 |