2014-09-23 34 views
1

目前,我有一个Java应用程序需要从目录复制文件并将其放置在桌面上。我有这个方法从Windows,Mac和Linux上的位置检索文件

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,以及我如何重组我的代码?

回答

1

你可以使用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()); 
} 
0

您可以确定使用

System.getProperty("os.name") 
相关问题