问题
So i have made an application which performs some reading/writing to files. I want to make the Path Traversal as independent of O.S.
Different operating systems use different characters as file separators. For example, Microsoft Windows systems use "\"
, while UNIX systems use "/"
. When applications have to run on different platforms, the use of hardcoded file separators can lead to incorrect execution of application logic.
So i came up with using a double backward slash '\\'
. But now i came to that i can use
public static final String FILE_SEPARATOR = System.getProperty("file.separator");
public static final String PATH_SEPARATOR = System.getProperty("path.separator");
reference here http://www.javapractices.com/topic/TopicAction.do?Id=38.
Am i wrong ? What is the correct way ?
回答1:
One simple way is to use File.separator
for the separator between path names and File.pathSeparator
for the separator between paths. Those are identical to the "file.separator"
and "path.separator"
properties.
System.getProperty("file.separator")
would return "/" on UNIX and "\" on Windows.
System.getProperty("path.separator")
would return ":" on UNIX and ";" on Windows.
You may check http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html.
回答2:
In java depending on which system your programm is executed on, the separator may be different.
For example, on Linux Filesystem it is the '/' separator.
On Windows Filesystem it is the '\' separator.
So if you use the File.separator you will be sure the right separator will be used and no problem will occur this way.
来源:https://stackoverflow.com/questions/24137446/what-is-better-using-a-double-backward-slash-as-file-seperator-or-files