2011-11-25 51 views
0

我有複製文件的方法:的Java複製文件強行

private static void copy(final String source, final String destination) { 
    try { 
     final File f1 = new File(source); 
     final File f2 = new File(destination); 
     final InputStream in = new FileInputStream(f1); 
     final OutputStream out = new FileOutputStream(f2); 
     final byte[] buf = new byte[1024]; 
     int len; 
     while ((len = in.read(buf)) > 0) { 
      out.write(buf, 0, len); 
     } 
     in.close(); 
     out.close(); 
    } catch (final FileNotFoundException ignored) { 
    } catch (final IOException ignored) {} 
} 

有沒有辦法複製到目錄時,我可以覆蓋「訪問被拒絕」的錯誤?

注:我只需要這個Windows電腦。

+0

你確定要嗎?我建議不要這樣做,而是記錄您的工具/應用程序必須以適當的權限執行。 –

回答

3

否。如果您使用的是UNIX,則需要以具有該目錄寫入權限的用戶身份運行該程序。只是好奇,你爲什麼要重寫文件系統權限?爲什麼不使用適當的權限?

+0

我想將文件複製到啓動目錄。有點像Skype有什麼選擇在啓動時打開。唯一的問題是,在Windows 7和可能的Windows Vista上,管理員需要確認副本。 – Confiqure

0
public static void copyFile(File source, File dest) throws IOException { 
    FileChannel inputChannel = null; 
    FileChannel outputChannel = null; 

    try { 
     inputChannel = new FileInputStream(source).getChannel(); 
     outputChannel = new FileOutputStream(dest).getChannel(); 
     outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); 
    } finally { 
     inputChannel.close(); 
     outputChannel.close(); 
    } 
}