1、删除
2 P% u3 a1 G" k( X. u5 ~在java中,删除文件非常简单,仅仅是一个方法调用& a! _, a; Z/ O# B, ]
new File("file path").delete(); 2、移动
3 ?4 V8 r x* p w移动文件和删除文件同样简单,也只需要一个方法调用: new File("source file path").renameTo(new File("destination file path")); 3、复制4 Y! Y$ B+ ~7 m1 }4 c. D1 K/ g4 v
Java中复制文件需要比较复杂的操作,因为没有API来完成该任务。下面是一个将文件从一个目录复制到另一个目录的例子: public void copyFiles(String source, String destination) throws IOException {
9 M \) M$ r- I& _/ K' t- z5 L+ MFile srcDir = new File(source);3 v8 F, b; \ D- ?5 J1 X/ |
File[] files = srcDir.listFiles(); FileChannel in = null;
( m+ ~0 I0 O2 H6 n0 ?4 P1 i) S TFileChannel out = null;
0 c2 |( ^( o7 c% qfor (File file : files) {; L4 d( \: V" |8 B. j2 l( p
try {
4 d0 C9 ~ @7 @. s$ tin = new FileInputStream(file).getChannel();
! ~# g1 h5 x! RFile outFile = new File(destination, file.getName());
. y: H5 s H( Fout = new FileOutputStream(outFile).getChannel();
9 H2 a$ _5 X! `7 I6 l+ a) uin.transferTo(0, in.size(), out);
1 ^ H0 x& h7 J) M! `' x! J( w} finally {% }! F7 a$ n* g. [ ? X
if (in != null)
! H! L5 ^" I' h( n1 t9 P% E* k. bin.close();
/ G1 n. K5 u# Y" ?+ m: {5 D yif (out != null)
6 u4 B) K7 I! ^6 D7 h/ Zout.close();7 L1 `- b8 P$ ?+ v( R8 I+ O
}2 O/ X3 t6 ?/ q* d3 F
}; R3 d7 K+ Z9 X y
}上面的代码中使用Java5中的NIO API,它能快速的完成任务
/ ^' B" d5 u5 { |