在Java代码中将Windows样式路径转换为Unix路径

在Java代码中将Windows样式路径转换为Unix路径

问题描述:

我正在使用旨在在Windows上运行的Java代码进行工作,该Java代码包含许多使用Windows样式路径"System.getProperty("user.dir")\ trash \ blah"对文件的引用.我负责对其进行调整并在Linux中进行部署.有没有一种有效的方法可以将所有这些路径(\)转换为Unix样式(/),例如在"System.getProperty(" user.dir)/trash/blah"中.也许,在Java或Linux中某些配置将\用作/.

I am working in a java code that was designed to run on windows and contains a lot of references to files using windows style paths "System.getProperty("user.dir")\trash\blah". I am in charge to adapt it and deploy in linux. Is there an efficient way to convert all those paths(\) to unix style (/) like in "System.getProperty("user.dir")/trash/blah". Maybe, some configuration in java or linux to use \ as /.

我的方法是使用Path对象保存路径信息,处理串联和相对路径.然后,调用Path的toString()以获取路径String.

My approach is to use the Path object to hold the path information, handle concatenate and relative path. Then, call Path's toString() to get the path String.

为了转换路径分隔符,我更喜欢使用apache公共io库的FilenameUtils.它提供了三个有用的功能:

For converting the path separator, I preferred to use the apache common io library's FilenameUtils. It provides the three usefule functions:

String  separatorsToSystem(String path);
String  separatorsToUnix(String path);
String  separatorsToWindows(String path)

请查看代码段,以了解相对路径,toString和分隔符的更改:

Please look the code snippet, for relative path, toString, and separator changes:

private String getRelativePathString(String volume, Path path) {
  Path volumePath = Paths.get(configuration.getPathForVolume(volume));
  Path relativePath = volumePath.relativize(path);
  return FilenameUtils.separatorsToUnix(relativePath.toString());
}