有没有一个Java实用程序将转换字符串路径使用正确的文件分隔符字符? [英] Is there a Java utility which will convert a String path to use the correct File separator char?

查看:252
本文介绍了有没有一个Java实用程序将转换字符串路径使用正确的文件分隔符字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了许多用Java处理文件的类。我正在一个Linux机器上工作,并且正在愉快地输入新文件(path / to / some / file); 。当提交时,我意识到项目中的其他开发人员正在使用Windows。现在我想调用一个方法,它可以接受一个形式为/ path / to / some / file的字符串,并根据操作系统返回一个正确的分开的路径。



例如:

path / to / some / file变成<$在Windows上使用c $ c>path \\\\\\\\\\\\\\\\\\。
在Linux上它只是返回给定的String。 p>

我意识到不需要很长时间就可以做出正确的表达式,但我不打算重新发明轮子,而更喜欢经过正确测试的解决方案。如果它是内置在JDK中的话,那将会很好,但是如果它是一个小的F / OSS库的一部分,那也可以。

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

Apache Commons来救援(再次)。 Commons IO方法 FileNameUtils separatorsToSystem()会做你想做的。



不用多说,Apache Commons IO会做更多的事情,值得一看。


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.

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

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.

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

解决方案

Apache Commons comes to the rescue (again). The Commons IO method FileNameUtils.separatorsToSystem() will do what you want.

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

这篇关于有没有一个Java实用程序将转换字符串路径使用正确的文件分隔符字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆