2014-09-23 55 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") 
相關問題