[英]Retrieve File from Location on Windows, Mac and Linux
Currently, I have a Java application that needs to copy a file from a directory and place it on the Desktop. 当前,我有一个Java应用程序,需要从目录复制文件并将其放置在桌面上。 I have this method 我有这种方法
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();
}
}
and I call it like below. 我这样称呼它。
copyFileUsingFileStreams(new File("C:/Program Files (x86)/MyProgram/App_Data/Session.db"), new File(System.getProperty("user.home") + "/Desktop/Session.db"));
This works perfectly on Windows. 这在Windows上完美运行。 However, I want to be able to do the exact same thing on Mac and Linux machines as well (location is /opt/myprogram/App_Data/Session.db). 但是,我也希望能够在Mac和Linux计算机上执行完全相同的操作(位置为/opt/myprogram/App_Data/Session.db)。 How can I assess whether the machine running is Windows or Mac/Linux, and how do I restructure my code accordingly? 如何评估运行的计算机是Windows还是Mac / Linux,以及如何相应地重组代码?
You can get the OS info using System.getProperty
like 您可以使用System.getProperty
来获取操作系统信息,例如
String property = System.getProperty("os.name");
Moreover you can use Files.copy() to simplify your code(and if you want more control then use StandardCopyOption ). 此外,您可以使用Files.copy()来简化代码(如果需要更多控制,请使用StandardCopyOption )。 eg 例如
Files.copy(src, Paths.get("/opt/myprogram/App_Data/Session.db"));
so your updated code can look something like this 这样您更新后的代码可以看起来像这样
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());
}
您可以使用确定操作系统名称
System.getProperty("os.name")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.