|
1、删除
$ y6 @8 J) X3 F: c; [8 C# b在java中,删除文件非常简单,仅仅是一个方法调用
9 j, Y/ [$ I# `' j+ I3 ~new File("file path").delete(); 2、移动* ~0 g- Q$ U' ^, j4 _7 s# F0 p
移动文件和删除文件同样简单,也只需要一个方法调用: new File("source file path").renameTo(new File("destination file path")); 3、复制
! ~8 u; n2 S: f, gJava中复制文件需要比较复杂的操作,因为没有API来完成该任务。下面是一个将文件从一个目录复制到另一个目录的例子: public void copyFiles(String source, String destination) throws IOException {
$ l( U; O% t" e- C* SFile srcDir = new File(source);
9 X) o/ k9 \; y% Q1 I* I! xFile[] files = srcDir.listFiles(); FileChannel in = null;
/ g# H. j& ~% k; y- B! x, z GFileChannel out = null;
# [0 ^- R' G" h! K' Ffor (File file : files) {9 Y: t+ w0 _# h. Q- N/ b; I
try {% a s+ v' F# `8 R3 W
in = new FileInputStream(file).getChannel();: i2 f+ q- s; S! {. `4 o! d
File outFile = new File(destination, file.getName());6 n1 F+ X3 p9 M. H+ [
out = new FileOutputStream(outFile).getChannel();
) d3 e. F) Y) Y8 Win.transferTo(0, in.size(), out);
. U ^. W" `/ P- B6 t2 d O _} finally {7 v8 t- W; o4 M' i
if (in != null)
) {; i" }% ?7 M) fin.close();3 n3 \/ T; F5 c6 A* Y8 h
if (out != null)' P3 U% v3 o8 X! x! o7 V
out.close();
( }. g: j( H$ C0 B$ a/ p( k& ~}
. m) x1 \% K5 f b C7 _ X6 l$ [}
* D" J3 O3 j. w% [+ N}上面的代码中使用Java5中的NIO API,它能快速的完成任务
' n! G4 O' X3 d) v. x! r |