目前,我有一个 Java 应用程序,需要从目录复制文件并将其放在桌面上。我有这个方法
public static void copyFileUsingFileStreams(File source, File dest) throws IOException {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(source);
output = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) { output.write(buf, 0, bytesRead); }
}
finally {
input.close();
output.close();
}
}
我这样调用它。
copyFileUsingFileStreams(new File("C:/Program Files (x86)/MyProgram/App_Data/Session.db"), new File(System.getProperty("user.home") + "/Desktop/Session.db"));
这在 Windows 上完美运行。但是,我希望能够在 Mac 和 Linux 计算机上执行完全相同的操作(位置为/opt/myprogram/App_Data/Session.db)。如何评估运行的计算机是 Windows 还是 Mac/Linux,以及如何相应地重构我的代码?
最佳答案
您可以使用System.getProperty
获取操作系统信息,例如
String property = System.getProperty("os.name");
此外,您可以使用 Files.copy()简化您的代码(如果您想要更多控制,请使用 StandardCopyOption )。例如
Files.copy(src, Paths.get("/opt/myprogram/App_Data/Session.db"));
所以你更新后的代码看起来像这样
public static void copyFileUsingFileStreams(File source, File dest) throws IOException {
String property = System.getProperty("os.name");
if (property.equals("Linux")) {
dest = Paths.get("/opt/myprogram/App_Data/Session.db").toFile();
}
//add code to adjust dest for other os.
Files.copy(source.toPath(), dest.toPath());
}
关于java - 从 Windows、Mac 和 Linux 上的位置检索文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26002932/