What is better ? Using a double backward slash ('\\') as file seperator or Files.seperator to remove O.S. Dependency while working with files in java

北慕城南 提交于 2021-02-05 07:00:43

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!