반응형
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
반응형
'programing' 카테고리의 다른 글
SELECT 포함 삽입 (0) | 2022.09.06 |
---|---|
ByteBuffer의 플립 방식의 목적은 무엇입니까? (그리고 왜 "플립"이라고 부릅니까?) (0) | 2022.09.06 |
Intelij IDEA, 프로젝트의 모든 코드 포맷 (0) | 2022.09.06 |
Python 3에서 int를 바이트로 변환하는 중 (0) | 2022.09.06 |
Windows에서 MySQL 화면 콘솔을 지우려면 어떻게 해야 합니까? (0) | 2022.09.05 |