在Java代码中将Windows样式路径转换为Unix路径 [英] Convert Windows style path into unix path in java code

查看:884
本文介绍了在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());
}

这篇关于在Java代码中将Windows样式路径转换为Unix路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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