About Java File.separator

in Windows path separator and Linux path separator is different, when the absolute path is used directly, cross-platform will be exposed “No such file or diretory” exception.

File
File file1 = new File (“C:\ TMP \test.txt”);
File file1 = new File (“C:\ TMP \test.txt”)

File file2 = new File (“/ TMP /test.txt”);
File file2 = new File (“/ TMP /test.txt”);

if cross-platform is considered, it is best to say:
File myFile = new File(“C:” + file.separator + “TMP” + file.separator, “test.txt”);
File myFile = new File(“C:” + file.separator + “TMP” + file.separator, “test.txt”);

The

File class has several static fields that are similar to separator, which are system related and should be used as far as possible in programming.

separatorChar

public static final char separatorChar

is the default name separator associated with the system. This field is initialized to the first character that contains the system property file.separator value. On UNIX systems, the value of this field is ‘/’; On Microsoft Windows, it is ‘\’.

separator

public static final String separator

is the system-specific default name separator, which is represented as a string for convenience. This string contains only one character, separatorChar.

pathSeparatorChar

public static final char pathSeparatorChar

is the system-dependent path separator. This field is initialized as the first character that contains the system property path.separator value. This character is used to separate filenames in a given file sequence in the form of a path list. On UNIX systems, this field is ‘:’; On Microsoft Windows, it is ‘; ‘.

pathSeparator

public static final String pathSeparator

is the system-dependent path separator, which is represented as a string for convenience. This string contains only one character, pathSeparatorChar.

☞ warm prompt: to return to my blog index

Read More: