1、删除 L$ Y' d$ _3 j8 B9 v, B
在java中,删除文件非常简单,仅仅是一个方法调用( e( r- b/ N1 E# e
new File("file path").delete(); 2、移动
3 |5 K" l( P' @; h移动文件和删除文件同样简单,也只需要一个方法调用: new File("source file path").renameTo(new File("destination file path")); 3、复制6 u+ `! H- N" v* A2 a
Java中复制文件需要比较复杂的操作,因为没有API来完成该任务。下面是一个将文件从一个目录复制到另一个目录的例子: public void copyFiles(String source, String destination) throws IOException {
+ L; R% ?# x' DFile srcDir = new File(source);
: X3 I# ^! I/ d$ D* E7 u3 p2 PFile[] files = srcDir.listFiles(); FileChannel in = null;& `2 [+ o* d: M/ A1 y# P3 a6 V. |4 t
FileChannel out = null;
4 z. w2 x/ P! @5 Z$ Pfor (File file : files) {
9 j+ @+ \/ T! Q) ntry {( o# V9 Y6 D/ x, a
in = new FileInputStream(file).getChannel();
8 s- ?7 o5 w. ~File outFile = new File(destination, file.getName());
- d/ R% I3 x5 A1 e oout = new FileOutputStream(outFile).getChannel();8 x, R/ W% w9 s; u5 a! K
in.transferTo(0, in.size(), out);6 @% o- R, D0 D2 l0 k( |0 p* \ q
} finally {
: R+ P0 d$ R& e' E# G6 Hif (in != null)
% y# X( M8 W. g1 F4 Yin.close();8 o* D- U" p7 a' c7 f, q q. T0 m
if (out != null)1 y2 ^0 s( o5 r v4 Y9 i
out.close();
8 l% z5 ^' G; B6 l2 g}0 L8 l/ S4 L8 T8 ]" q; p
}! ^0 h# r6 S( y( Z) [
}上面的代码中使用Java5中的NIO API,它能快速的完成任务
( a. w/ x- v4 R+ ^; E# {( ` |