IT

경로에서 File.separator와 슬래시의 차이점

lottoking 2020. 5. 15. 08:21
반응형

경로에서 File.separator와 슬래시의 차이점


Java Path-String에서 사용 File.separator과 일반 의 차이점은 무엇입니까 /?

이중 백 슬래시 \\플랫폼 독립성 과 달리 두 버전 모두 Windows 및 Unix에서 작동하기 때문에 이유가 아닌 것 같습니다.

public class SlashTest {
    @Test
    public void slash() throws Exception {
        File file = new File("src/trials/SlashTest.java");
        assertThat(file.exists(), is(true));
    }

    @Test
    public void separator() throws Exception {
        File file = new File("src" + File.separator + "trials" + File.separator + "SlashTest.java");
        assertThat(file.exists(), is(true));
    }
}

/유닉스와 윈도우에서 작동 한다면 , 왜 그 질문을 바꾸어 놓아야 File.separator합니까?


파일 처리를위한 Java 라이브러리를 사용하면 /모든 플랫폼에서 안전하게 백 슬래시가 아닌 슬래시를 사용할 수 있습니다. 라이브러리 코드는 사물을 내부적으로 플랫폼 별 경로로 변환하는 것을 처리합니다.

File.separator그러나 UI 에 사용 하는 것이 좋습니다. Java에 의미가있는 것보다는 OS에 의미가있는 것을 사람들에게 보여주는 것이 가장 좋습니다.

업데이트 : 5 분 동안 검색하면 "항상 슬래시를 사용할 수 있습니다"동작을 찾을 수 없었습니다. 이제, 나는 그것이 문서화 된 것을 보았지만, 공식적인 참고 자료를 찾지 못했을 때 (내 기억이 완벽하지 않기 때문에) 사용 File.separator하는 것을 알고 있기 때문에 사용을 고수 할 것입니다.


당신은 사용 File.separator언젠가는 당신의 프로그램이 개발 플랫폼에서 실행할 수 있기 때문에 먼 땅, 말 울음 소리와 소는 모든 엘리베이터를 운영 이상한 일들과 낯선 사람들의 땅. 이 땅에서 사람들은 전통적으로 ":"문자를 파일 구분 기호로 사용 했으므로 JVM은 자신의 소원에 충실하게 따릅니다.


File.separator를 사용하여 파일 이름을 참조하는 것은 과도하지만 (먼 곳을 상상하는 사람들에게는 JVM 구현이 Windows가 jvm을으로 대체 /하는 :것과 똑같이 JVM 구현을 대체한다고 생각 합니다 \).

그러나 때로는 파일 참조를 작성하지 않고 파일 참조를 가져 와서 구문 분석해야하며이를 수행하려면 플랫폼의 구분 기호를 알아야합니다. File.separator가 그렇게 도와줍니다.


이제 코드를 검사 해 봅시다.
File.java라인 428 ~ 435 File.<init>:

String p = uri.getPath();
if (p.equals(""))
    throw new IllegalArgumentException("URI path component is empty");

// Okay, now initialize
p = fs.fromURIPath(p);
if (File.separatorChar != '/')
p = p.replace('/', File.separatorChar);

그리고 fs/*(FileSystem)*/.fromURIPath()문서를 읽겠습니다 :

java.io.FileSystem
public abstract String fromURIPath (String path)
필요한 경우 지정된 URI 경로 문자열을 사후 처리합니다. 예를 들어, "/ c : / foo"를 "c : / foo"로 변환하기 위해 win32에서 사용됩니다. 경로 문자열에는 여전히 슬래시 구분 기호가 있습니다. File 클래스의 코드는이 메소드가 리턴 된 후이를 변환합니다.

이것은 FileSystem.fromURIPath()Windows에서만 URI 경로에 대한 포스트 처리를 수행 한다는 것을 의미 하며 다음 줄에 있기 때문입니다.

p = p.replace('/', File.separatorChar);

각 '/'를 시스템 종속으로 대체 seperatorChar하므로 항상 모든 OS 에서 '/'가 안전하다는 것을 확신 할 수 있습니다 .


글쎄, Unix와 Windows (Portable devices 등)보다 OS가 더 많고 Java는 이식성으로 유명합니다. 모범 사례는이를 사용하는 것이므로 JVM이 해당 OS에 가장 적합한 것을 결정할 수 있습니다.


그것은 도중에 큰 차이를 만들지 않지만 돌아 오는 길에 있습니다.

새 File (String path)에서 '/'또는 '\'를 사용할 수 있지만 File.getPath ()는 그 중 하나만 제공합니다.


파티에 늦었다. JDK 1.8 및 Eclipse MARS 1이 설치된 Windows 10을 사용
하고 있습니다.

getClass().getClassLoader().getResourceAsStream("path/to/resource");

작품과

getClass().getClassLoader().getResourceAsStream("path"+File.separator+"to"+File.separator+"resource");

작동하지 않습니다

getClass().getClassLoader().getResourceAsStream("path\to\resource");

작동하지 않습니다. 마지막 두 개는 동일합니다. 그래서 ... File.separator를 사용하지 않는 좋은 이유가 있습니다.


휴대가 간편하고 단순합니다.


"프로그래머 용 Java SE8"은 Java 가 어느 쪽에도 대처할 것이라고 주장 합니다. (pp. 480, 마지막 단락). 이 예는 다음과 같이 주장합니다.

c:\Program Files\Java\jdk1.6.0_11\demo/jfc

잘 파싱합니다. 마지막 (유닉스 스타일) 구분 기호를 기록해 두십시오.

그것은 끈적 거리며 아마도 오류가 발생하기 쉽지만 그것이 (Deitel과 Deitel) 주장입니다.

I think the confusion for people, rather than Java, is reason enough not to use this (mis?)feature.


As the gentlemen described the difference with variant details.

I would like to recommend the use of the Apache Commons io api, class FilenameUtils when dealing with files in a program with the possibility of deploying on multiple OSs.


The pathname for a file or directory is specified using the naming conventions of the host system. However, the File class defines platform-dependent constants that can be used to handle file and directory names in a platform-independent way.

Files.seperator defines the character or string that separates the directory and the file com- ponents in a pathname. This separator is '/', '\' or ':' for Unix, Windows, and Macintosh, respectively.


If you are using Java 7, checkout Path.resolve() and Paths.get().


Using File.separator made Ubuntu generate files with "\" on it's name instead of directories. Maybe I am being lazy with how I am making files(and directories) and could have avoided it, regardless, use "/" every time to avoid files with "\" on it's name


If you are trying to create a File from some ready path (saved in database, per example) using Linux separator, what should I do?

Maybe just use the path do create the file:

new File("/shared/folder/file.jpg");

But Windows use a different separator (\). So, is the alternative convert the slash separator to platform independent? Like:

new File(convertPathToPlatformIndependent("/shared/folder"));

This method convertPathToPlatformIndependent probably will have some kind of split by "/" and join with File.separator.

Well, for me, that's not nice for a language that is platform independent (right?) and Java already support the use of / on Windows or Linux. But if you are working with paths and need to remember to this conversion every single time this will be a nightmare and you won't have any real gain for the application on the future (maybe in the universe that @Pointy described).

참고URL : https://stackoverflow.com/questions/2417485/difference-between-file-separator-and-slash-in-paths

반응형