是否有 Java 实用程序可以将字符串路径转换为使用正确的文件分隔符字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1697303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:41:14  来源:igfitidea点击:

Is there a Java utility which will convert a String path to use the correct File separator char?

javastringfile-iocross-platformjdk1.6

提问by Grundlefleck

I have developed a number of classes which manipulate files in Java. I am working on a Linux box, and have been blissfully typing new File("path/to/some/file");. When it came time to commit I realised some of the other developers on the project are using Windows. I would now like to call a method which can take in a String of the form "/path/to/some/file"and, depending on the OS, return a correctly separated path.

我开发了许多在 Java 中操作文件的类。我正在 Linux 机器上工作,并且一直很高兴地输入new File("path/to/some/file");. 当需要提交时,我意识到该项目的其他一些开发人员正在使用 Windows。我现在想调用一个方法,该方法可以接受表单的字符串,"/path/to/some/file"并根据操作系统返回正确分隔的路径。

For example:
"path/to/some/file"becomes "path\\to\\some\\file"on Windows.
On Linux it just returns the given String.

例如:在 Windows 上
"path/to/some/file"变为"path\\to\\some\\file"
在 Linux 上,它只返回给定的字符串。

I realise it wouldn't take long to knock up a regular expression that could do this, but I'm not looking to reinvent the wheel, and would prefer a properly tested solution. It would be nice if it was built in to the JDK, but if it's part of some small F/OSS library that's fine too.

我意识到敲出可以做到这一点的正则表达式不会花很长时间,但我不想重新发明轮子,并且更喜欢经过适当测试的解决方案。如果它内置在 JDK 中会很好,但如果它是某个小型 F/OSS 库的一部分,那也很好。

So is there a Java utility which will convert a String path to use the correct File separator char?

那么是否有一个 Java 实用程序可以将字符串路径转换为使用正确的文件分隔符字符?

采纳答案by Brian Agnew

Apache Commonscomes to the rescue (again). The Commons IOmethod FilenameUtils.separatorsToSystem(String path)will do what you want.

Apache Commons来救援(再次)。该Commons IO方法FilenameUtils.separatorsToSystem(String path)将执行您想要的操作。

Needless to say, Apache Commons IOwill do a lot more besides and is worth looking at.

不用说,Apache Commons IO除此之外还会做很多事情,值得一看。

回答by Thomas Jung

A "/path/to/some/file"actually worksunder Windows Vista and XP.

A"/path/to/some/file"实际上可以在 Windows Vista 和 XP 下运行。

new java.io.File("/path/to/some/file").getAbsoluteFile()

> C:\path\to\some\file

But it is still not portableas Windows has multiple roots. So the root directory has to be selected in some way. There should be no problem with relative paths.

但它仍然不可移植,因为 Windows 有多个。所以必须以某种方式选择根目录。相对路径应该没有问题。

Edit:

编辑:

Apache commons iodoes nothelp with envs other than unix & windows. Apache io source code:

Apache commons io对unix 和 windows 以外的环境没有帮助。Apache io 源代码

public static String separatorsToSystem(String path) { 
    if (path == null) {
     return null;
    }
    if (isSystemWindows()) {
      return separatorsToWindows(path);
    } else {
      return separatorsToUnix(path);
    }
}

回答by Adam

Do you have the option of using

您是否可以选择使用

System.getProperty("file.separator")

to build the string that represents the path?

构建代表路径的字符串?

回答by Dimitri

Shouldn't it be enough to say:

难道说:

"path"+File.Seperator+"to"+File.Seperator+"some"+File.Seperator+"file"

回答by Gigas64

With the new Java 7 they have included a class called Paths this allows you to do exactly what you want (see http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html)

在新的 Java 7 中,他们包含了一个名为 Paths 的类,这使您可以完全按照自己的意愿行事(请参阅http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

here is an example:

这是一个例子:

String rootStorePath = Paths.get("c:/projects/mystuff/").toString();

回答by Daniel Winterstein

This is what Apache commons-io does, unrolled into a couple of lines of code:

这就是 Apache commons-io 所做的,展开成几行代码:

String separatorsToSystem(String res) {
    if (res==null) return null;
    if (File.separatorChar=='\') {
        // From Windows to Linux/Mac
        return res.replace('/', File.separatorChar);
    } else {
        // From Linux/Mac to Windows
        return res.replace('\', File.separatorChar);
    }
}

So if you want to avoid the extra dependency, just use that.

所以如果你想避免额外的依赖,就使用它。

回答by java-addict301

For anyone trying to do this 7 years later, the apache commons separatorsToSystem method has been moved to the FilenameUtils class:

对于 7 年后尝试这样做的任何人,apache commons separatorsToSystem 方法已移至 FilenameUtils 类:

FilenameUtils.separatorsToSystem(String path)

回答by John Perczyk

String fileName = Paths.get(fileName).toString();

Works perfectly with Windows at least even with mixed paths, for example

例如,至少即使使用混合路径也能与 Windows 完美配合

c:\users\username/myproject\myfiles/myfolder

c:\用户\用户名/我的项目\我的文件/我的文件夹

becomes

变成

c:\users\username\myproject\myfiles\myfolder

Sorry haven't check what Linux would make of the above but there again Linux file structure is different so you wouldn't search for such a directory

抱歉,还没有检查 Linux 会对上述内容产生什么影响,但 Linux 文件结构再次不同,因此您不会搜索这样的目录

回答by Stan Towianski

I think there is this hole in Java Paths.

我认为 Java Paths 中有这个漏洞。

String rootStorePath = Paths.get("c:/projects/mystuff/").toString();

works if you are running it on a system that has the file system you need to use. As pointed out, it used the current OS file system.

如果您在具有您需要使用的文件系统的系统上运行它,则可以工作。正如所指出的,它使用了当前的操作系统文件系统。

I need to work with paths between windows and linux, say to copy a file from one to another. While using "/" every works I guess if you are using all Java commands, but I need to make an sftp call so using / or file.separatoretc... does not help me. I cannot use Path()because it converts mine to the default file system I am running on "now".

我需要处理 Windows 和 linux 之间的路径,比如将文件从一个复制到另一个。在使用“/”时,如果您使用所有 Java 命令,我猜每个都可以工作,但是我需要进行 sftp 调用,因此使用 / 或file.separator等...对我没有帮助。我无法使用,Path()因为它将我的转换为我在“现在”上运行的默认文件系统。

What Java needs is:
on windows system:

Java需要的是:
在windows系统上:

Path posixPath = Paths.get("/home/mystuff", FileSystem.Posix );
stays /home/mystuff/  and does not get converted to \home\mystuff

on linux system:
String winPath = Paths.get("c:\home\mystuff", FileSystem.Windows).toString();

stays c:\home\mystuffand does not get converted to /c:/home/mystuff

停留c:\home\mystuff并且不会被转换为/c:/home/mystuff

similar to working with character sets:

类似于使用字符集:

URLEncoder.encode( "whatever here", "UTF-8" ).getBytes();

P.S. I also do not want to load a whole apache io jar file to do something simple either. In this case they do not have what I propose anyways.

PS我也不想加载整个apache io jar文件来做一些简单的事情。在这种情况下,他们无论如何都没有我的建议。

回答by Daniel De León

I create this function to check if a String contain a \character then convert them to /

我创建了这个函数来检查一个字符串是否包含一个\字符,然后将它们转换为/

public static String toUrlPath(String path) {
  return path.indexOf('\') < 0 ? path : path.replace('\', '/');
}

public static String toUrlPath(Path path) {
  return toUrlPath(path.toString());
}