当前,我有一个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
like获取操作系统信息
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());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句