Java에서의 결합 경로
인Python나는 두 가지 길을 함께 할 수 있다.os.path.join:
os.path.join("foo", "bar") # => "foo/bar"
자바에서도 같은 것을 얻으려고 노력하고 있습니다.OS이Unix,Solaris또는Windows:
public static void main(String[] args) {
Path currentRelativePath = Paths.get("");
String current_dir = currentRelativePath.toAbsolutePath().toString();
String filename = "data/foo.txt";
Path filepath = currentRelativePath.resolve(filename);
// "data/foo.txt"
System.out.println(filepath);
}
그럴 줄 알았어Path.resolve( )현재 디렉터리에 가입할 수 있습니다./home/user/test와 함께data/foo.txt만들기/home/user/test/data/foo.txt제가 뭘 잘못 알고 있는 거죠?
현재 디렉토리를 취득하기 위한 원래 솔루션이empty String동작합니다.단, 이 경우,user.dir현재 디렉토리의 속성 및user.home홈 디렉토리용입니다.
Path currentPath = Paths.get(System.getProperty("user.dir"));
Path filePath = Paths.get(currentPath.toString(), "data", "foo.txt");
System.out.println(filePath.toString());
출력:
/Users/user/coding/data/foo.txt
Java Path 클래스 문서:
패스가 1개의 이름 요소로만 구성되어 있는 경우 패스는 빈 경로로 간주됩니다.
empty. 를 사용하여 파일에 액세스합니다.empty path is equivalent to accessing the default directory파일 시스템입니다.
왜죠Paths.get("").toAbsolutePath()작동하다
빈 문자열이 에 전달된 경우Paths.get(""), 반환된Path개체에 빈 경로가 포함되어 있습니다.하지만 우리가 전화했을 때Path.toAbsolutePath()패스 길이가 0보다 큰지 여부를 확인합니다.그렇지 않은 경우,user.dir현재 경로를 반환합니다.
Unix 파일 시스템 구현 코드는 다음과 같습니다.UnixPath.ToAbsolutePath()
기본적으로는,Path현재 디렉토리 경로를 해결한 후 다시 instance를 실행합니다.
또, 다음의 것을 사용하는 것을 추천합니다.File.separatorChar플랫폼 독립 코드의 경우.
Path currentRelativePath = Paths.get("");
Path currentDir = currentRelativePath.toAbsolutePath(); // <-- Get the Path and use resolve on it.
String filename = "data" + File.separatorChar + "foo.txt";
Path filepath = currentDir.resolve(filename);
// "data/foo.txt"
System.out.println(filepath);
출력:
/Users/user/coding/data/foo.txt
Paths#get(String first, String... more) 상태,
경로 스트링 또는 경로 스트링을 형성하여 결합되었을 때 일련의 문자열이
Path....
첫 번째가 빈 문자열이고 더 많은 문자열이 비어 있지 않은 경우 빈 경로를 나타내는 가 반환됩니다.
현재의 유저 디렉토리를 취득하려면 , 간단하게 사용할 수 있습니다.System.getProperty("user.dir").
Path path = Paths.get(System.getProperty("user.dir"), "abc.txt");
System.out.println(path);
게다가.getmethod는 가변 길이 인수를 사용합니다.String이것은 후속 경로 문자열을 제공하기 위해 사용됩니다.그래서 만들기 위해서Path위해서/test/inside/abc.txt다음과 같이 사용해야 합니다.
Path path = Paths.get("/test", "inside", "abc.txt");
특정 방법이 아닙니다.
Java 8 이상을 사용하는 경우 다음 두 가지 옵션이 있습니다.
a) java.util을 사용합니다.String Joiner(문자
StringJoiner joiner = new StringJoiner(File.pathSeparator); //Separator
joiner.add("path1").add("path2");
String joinedString = joiner.toString();
b) 사용String.join(File.pathSeparator, "path1", "path2");
Java 7 이하를 사용하는 경우 Apache Commons에서 commons-lang 라이브러리를 사용할 수 있습니다.String Utils 클래스에는 구분자를 사용하여 문자열을 결합하는 메서드가 있습니다.
c)StringUtils.join(new Object[] {"path1", "path2"}, File.pathSeparator);
사이드노트:Windows 에서는 Linux 패스 세퍼레이터 「/」를 사용할 수 있습니다(절대 패스는 「/C:/mydir1/mydir2」와 같습니다).항상 "/"를 사용하면 다음과 같은 프로토콜을 사용하는 경우 매우 유용합니다://
당신은 할 수 있다
// /root
Path rootPath = Paths.get("/root");
// /root/temp
Path temPath = rootPath.resolve("temp");
자세한 내용은 Path Sample UseCase를 참조하십시오.
가장 기본적인 방법은 다음과 같습니다.
Path filepath = Paths.get("foo", "bar");
.Paths.get("")는, 「」를 사용해 주세요.Paths.get(System.getProperty("user.dir"))는, 「 」Paths.get(System.getProperty("user.home")).
다음의 어프로치를 조합할 수도 있습니다.
Path filepath = Paths.get(
System.getProperty("user.home"), "data", "foo.txt");
수 있는 하지 않는 경로 은 Java를 입니다.Path::resolve(용 JavaDoc에 기재되어 있습니다).경로의 일부를 나타내는 문자열의 임의 길이 배열의 경우 Java Stream을 사용하여 이들을 결합할 수 있습니다.
private static final String[] pieces = {
System.getProperty("user.dir"),
"data",
"foo.txt"};
public static void main (String[] args) {
Path dest = Arrays.stream(pieces).reduce(
/* identity */ Paths.get(""),
/* accumulator */ Path::resolve,
/* combiner */ Path::resolve);
System.out.println(dest);
}
Java > = 11의 경우 이전 답변에서 제안했듯이 Paths.get 대신 Path.get을 사용하는 것이 좋습니다.Java 11 문서에서 인용:
이 클래스는 향후 릴리스에서 폐지될 수 있으므로 이 클래스에 정의된 get 메서드가 아닌 Path.of 메서드를 통해 취득하는 것이 좋습니다.
예를 들어 OS 경로 구분자에 따라 다음 항목이 "foo"와 "bar"에 연결됩니다.
import java.nio.file.Path;
...
Path fooBar = Path.of("foo", "bar");
언급URL : https://stackoverflow.com/questions/34459486/joining-paths-in-java
'programing' 카테고리의 다른 글
| htmlentity() vs. htmlspecialchars() (0) | 2023.02.05 |
|---|---|
| Java 8: Java.util.function의 TriFunction(및 kin)은 어디에 있습니까?아니면 대체방법이 뭐죠? (0) | 2023.02.05 |
| 오류 "filename"입니다.이 플랫폼에서는 지원되지 않는 휠입니다. (0) | 2023.02.05 |
| 가능한 한 간단한 방법으로 Matplotlib의 PyPlot에 범례 추가 (0) | 2023.02.05 |
| MySQL에서 날짜, 월, 연도 필드 만들기 (0) | 2023.02.05 |