我正在Windows中开发,并且必须在流程中的某个地方访问sftp(Linux)服务器。我做了一些逻辑准备要从sftp服务器复制的文件名,并且需要生成完整路径,因此我在代码中写了这一行:
Paths.get(configuration.getSftpServerConfiguration().getRemotePath(), filename).toString();
因为我在Windows上运行,所以使用Windows斜线生成的路径,例如\public\directory\filename.csv
我可以定义与Linux分隔符一起使用的路径吗? (我知道我可以自己连接“ /”,但对我来说这是一种不好的做法。)
查看此帖子:Is there a Java utility which will convert a String path to use the correct File separator char?
基本上FilenameUtils.separatorsToSystem(String path)
中的Apache Commons
,将有助于实现您想做的事情。
如果您不想导入整个依赖关系,这就是方法的作用:
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);
}
}
UPDATE:正如@Slaw所说,该解决方案仍然依赖于平台。您可以修改该方法以使用额外的参数,并确定是要使用“ Unix”还是“ Windows”输出字符串,如下所示:
String changeFileSeparators(String res, boolean toUnix) {
if (res==null) return null;
if (toUnix) {
// From Windows to Linux/Mac
return res.replace('/', '\\');
} else {
// From Linux/Mac to Windows
return res.replace('\\', '/');
}
}