用Java復制文件的標準簡潔方法?我一直感到困擾的是,在Java中復制文件的唯一方法是打開流、聲明緩沖區、讀取一個文件、循環它并將其寫入另一個蒸汽中。Web上到處都是類似的、但仍然略有不同的這種解決方案的實現。是否有更好的方法保持在Java語言的范圍內(這意味著不涉及執行操作系統特定的命令)?也許在一些可靠的開源實用程序包中,這至少會模糊這個底層實現,并提供一個單行解決方案?
3 回答

滄海一幻覺
TA貢獻1824條經驗 獲得超5個贊
public static void copyFile( File from, File to ) throws IOException { if ( !to.exists() ) { to.createNewFile(); } try ( FileChannel in = new FileInputStream( from ).getChannel(); FileChannel out = new FileOutputStream( to ).getChannel() ) { out.transferFrom( in, 0, in.size() ); }}
public static void copyFile( File from, File to ) throws IOException { Files.copy( from.toPath(), to.toPath() );}
添加回答
舉報
0/150
提交
取消