问题描述
因此,我制作了一个对文件进行一些读取/写入的应用程序.我想使路径遍历独立于O.S.
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.
不同的操作系统使用不同的字符作为文件分隔符.例如,Microsoft Windows系统使用"\"
,而UNIX系统使用"/"
.当应用程序必须在不同的平台上运行时,使用硬编码的文件分隔符可能会导致应用程序逻辑的错误执行.
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");
此处的参考 http://www.javapractices.com/topic/TopicAction.是吗?Id = 38 .
我错了吗?正确的方法是什么?
Am i wrong ? What is the correct way ?
推荐答案
一种简单的方法是使用 File.separator
作为路径名和 File.pathSeparator
之间的分隔符路径之间的分隔符.这些属性与"file.separator"
和"path.separator"
属性相同.
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")
在UNIX上将返回"/",在Windows上将返回"\".
System.getProperty("file.separator")
would return "/" on UNIX and "\" on Windows.
System.getProperty("path.separator")
在UNIX上将返回:",在;"中将返回;".在Windows上.
System.getProperty("path.separator")
would return ":" on UNIX and ";" on Windows.
您可以检查 http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html .
这篇关于什么是更好的 ?使用双反斜杠('\\')作为文件分隔符或Files.seperator来删除O.S.在Java中处理文件时的依赖性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!