1、删除
" Y6 s' j9 t/ d1 n- {在java中,删除文件非常简单,仅仅是一个方法调用
: R5 K7 b- s/ hnew File("file path").delete(); 2、移动
- y% D4 H8 W7 v: a" k: T% f$ j7 Z移动文件和删除文件同样简单,也只需要一个方法调用: new File("source file path").renameTo(new File("destination file path")); 3、复制& ]; [9 M9 }& j4 Y% [3 f1 x
Java中复制文件需要比较复杂的操作,因为没有API来完成该任务。下面是一个将文件从一个目录复制到另一个目录的例子: public void copyFiles(String source, String destination) throws IOException {9 S9 }8 r5 c0 d! {% P. {
File srcDir = new File(source);
/ l+ ^& f9 j: s" jFile[] files = srcDir.listFiles(); FileChannel in = null;
$ h- o) J3 N- [9 y& n" iFileChannel out = null;
4 @/ [) x; ~; J4 i- \for (File file : files) {
7 _; t$ h$ @7 b- Z$ Gtry {" b( D+ Q! k z! b" P. B* }
in = new FileInputStream(file).getChannel();" d9 n3 n! @% | `6 G
File outFile = new File(destination, file.getName());9 `% z+ j8 X* H3 M+ O
out = new FileOutputStream(outFile).getChannel();# r- I4 |5 V4 j1 ]# l7 Y5 |' ?
in.transferTo(0, in.size(), out);
" R2 Q5 n' q) ?& b. m) J9 G} finally {& P: A( V' a( ?5 y
if (in != null)
4 A1 ~3 t7 I/ e% q; E+ _ l9 oin.close();, r, C1 m% S1 V
if (out != null)! U5 R& G" t& x9 `4 M
out.close();
4 _. X9 Y4 i: j* T7 H' F}
+ e! [* M) o9 ~9 `3 A" [}& T1 r I/ s% K1 y# ]' w
}上面的代码中使用Java5中的NIO API,它能快速的完成任务
/ D1 V* b5 x# [7 Y- q |