【问题标题】:Window/linux path component separatingWindow/linux路径组件分离
【发布时间】:2013-04-10 10:23:46
【问题描述】:

我正在我的 linux 环境中编写一个路径分隔符,它旨在解析一个文件路径,它既可以是 linux 也可以是 windows 样式,这是我以前不知道的。目前我正在使用 File.separator 进行拆分,但这仅适用于我所在的平台...

我想知道是否有办法使用 Path 对象之类的东西来处理这个问题。

[...]
Node pathElement = nodeList.item(nodePos);
String path = pathElement.getTextContent();
String[] pathElements = path.split(File.separator);
String contentFileName = pathElements[pathElements.length - 1];
String parentFolderPath = xmlFiles[u].getParentFile().getAbsolutePath();
pathElement.setTextContent(parentFolderPath + File.separator + contentFileName);
[...]

编辑:我需要能够从 linux 中断 windows 样式路径,反之亦然。我也尝试使用Paths.getPath(...) 失败

查看上述代码的示例输出:

/input/ZIP_0bd78143-f6cd-473f-84f7-d0da09dc42aa/7634/c:\SharedFiles\7634\1

它使用 windows 路径作为文件名,因为它无法破坏它。如果可能,我会尽量避免花哨的逻辑来检测路径的类型。

【问题讨论】:

    标签: java linux windows string path


    【解决方案1】:

    因此,根据您的编辑,您可能需要检测给定 URI 处的文件系统,可能需要查看以下内容:

    http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystems.html

    【讨论】:

    • 这就是文件分隔符绑定到操作系统的问题。因此,如果我在 linux 上尝试破坏 Windows 样式路径,我将无法使用该属性
    • 该属性会根据 JVM 运行的环境而变化。来自 Oracle 网站上的文档:“分隔文件路径组件的字符。这是 UNIX 上的“/”和 Windows 上的“\”。我相信它和 File.separator 不一样。
    • 刚刚在linux和windows环境下试了一下,果然奏效了。
    • 似乎是一个简单的解决方案。只需使用“\”作为 windows 路径,使用“/”作为 UNIX 路径。
    猜你喜欢
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2019-03-24
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    相关资源
    最近更新 更多