Java Windows 中 Linux 环境的路径
Java Paths in Windows for Linux environment
我在 Windows 开发,在流程中的某个地方我必须访问 sftp (Linux) 服务器。
我做了一些逻辑来准备我必须从 sftp 服务器复制的文件名,我需要生成完整路径,因此我在我的代码中写了这一行:
Paths.get(configuration.getSftpServerConfiguration().getRemotePath(), filename).toString();
因为我 运行 在 Windows 上 Windows 生成的路径带有 Windows 斜杠,例如 \public\directory\filename.csv
我可以定义路径以使用 Linux 分隔符吗? (我知道我可以自己连接“/”,但在我看来这是一种不好的做法..)
检查此 post: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);
}
}
更新:
正如@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('/', '\');
}
}
我在 Windows 开发,在流程中的某个地方我必须访问 sftp (Linux) 服务器。 我做了一些逻辑来准备我必须从 sftp 服务器复制的文件名,我需要生成完整路径,因此我在我的代码中写了这一行:
Paths.get(configuration.getSftpServerConfiguration().getRemotePath(), filename).toString();
因为我 运行 在 Windows 上 Windows 生成的路径带有 Windows 斜杠,例如 \public\directory\filename.csv
我可以定义路径以使用 Linux 分隔符吗? (我知道我可以自己连接“/”,但在我看来这是一种不好的做法..)
检查此 post: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);
}
}
更新: 正如@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('/', '\');
}
}