Java 文件分隔符,文件路徑分隔符 File separator, separatorChar, pathSeparator, pathSeparatorChar

下面是File類的四個靜態變量;

File.separator: 和平臺相關,是一個字符串. 例如, ‘\’ 是在windows , ‘/’ 是在Unix.
File.separatorChar: 和上面一樣,但是char類型的.
File.pathSeparator: 路徑分隔符,例如一系列的類路徑 ‘:’ 是在Unix ,‘;’ 是在Windows.
File.pathSeparatorChar: 同上,但是爲char類型

/**
 * Java File separator, separatorChar, pathSeparator, pathSeparatorChar
 *  文件分隔符,文件路徑分隔符
 */
public class Test9 {
    public static void main(String[] args) {

        System.out.println("File.separator = "+ File.separator);
        System.out.println("File.separatorChar = "+File.separatorChar);
        System.out.println("File.pathSeparator = "+File.pathSeparator);
        System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);

        // 不是系統獨立的,只適用於 Unix環境
        File fileUnsafe = new File("tmp/abc.txt");

        //platform independent and safe to use across Unix and Windows
        // 平臺獨立獨立,可以同時在windows和Unix系統使用,使用File.separator的好處
        File fileSafe = new File("tmp"+File.separator+"abc.txt");

    }
}

參考

  • https://www.journaldev.com/851/java-file-separator-separatorchar-pathseparator-pathseparatorchar
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章