1、删除
" s o4 |% r" s$ ^2 A. g7 Z在java中,删除文件非常简单,仅仅是一个方法调用
8 l, f8 N& F; Y7 ]' Xnew File("file path").delete(); 2、移动
& m" f+ q! F9 R; W" J3 D移动文件和删除文件同样简单,也只需要一个方法调用: new File("source file path").renameTo(new File("destination file path")); 3、复制
1 ^4 y5 G% b8 W5 ?1 u* YJava中复制文件需要比较复杂的操作,因为没有API来完成该任务。下面是一个将文件从一个目录复制到另一个目录的例子: public void copyFiles(String source, String destination) throws IOException {
( \6 K, ~' ~6 p) i2 MFile srcDir = new File(source);
9 u. j3 H2 g! P7 E+ x S" xFile[] files = srcDir.listFiles(); FileChannel in = null;' Z( r, |) H$ G6 ~; P; q' e
FileChannel out = null;# l& X; [( H" C! |/ W
for (File file : files) {
# H- U7 O+ M/ D: ?! ytry {' |1 J: j; g; Y* U# \
in = new FileInputStream(file).getChannel();2 t7 u6 g9 u) L _0 i7 n" S9 M/ ?
File outFile = new File(destination, file.getName());
& h% h* C/ H0 a# B8 Oout = new FileOutputStream(outFile).getChannel();3 |& M& G9 ?% a. V- X! z9 w0 I6 r
in.transferTo(0, in.size(), out);" N% K1 k) X2 m- `0 X% G) C
} finally {6 H2 y9 Y% m) k
if (in != null)) M( h: ^; u( H9 J9 U
in.close();: T3 K- s7 n0 T6 ]0 O: ?% U
if (out != null)% J" h: e; d& _
out.close();
( W6 c( h; d3 r8 e: U* ~& P}
, o$ |' d+ ?0 t) X}1 u9 t7 o3 C+ h* o, h4 S, ]
}上面的代码中使用Java5中的NIO API,它能快速的完成任务 2 {& S/ D' O( L2 J, L
|