|
1、删除
0 g7 S0 n5 o: r8 }在java中,删除文件非常简单,仅仅是一个方法调用9 @$ M' F0 H9 C2 b& O
new File("file path").delete(); 2、移动
( ^% `- s" r0 a: Q& s7 i" J移动文件和删除文件同样简单,也只需要一个方法调用: new File("source file path").renameTo(new File("destination file path")); 3、复制( _3 C% p* \, _1 E7 P
Java中复制文件需要比较复杂的操作,因为没有API来完成该任务。下面是一个将文件从一个目录复制到另一个目录的例子: public void copyFiles(String source, String destination) throws IOException {
% v. p" X- n6 `. V( [2 HFile srcDir = new File(source);2 v E8 j& F7 l& B
File[] files = srcDir.listFiles(); FileChannel in = null;7 e) {% g3 E3 Y, Y r* T% w
FileChannel out = null;
; n- ^, T' u0 [for (File file : files) {7 Z# H$ Y( _( Z* G4 C8 ]
try {
; u5 ~% q6 g6 W* n& Yin = new FileInputStream(file).getChannel();
! Q. e+ n" Z: i+ D6 TFile outFile = new File(destination, file.getName());# v+ o1 w F3 A* R( [! ^& z
out = new FileOutputStream(outFile).getChannel();
1 ?& v! N- o; X; G# ?5 @. h9 D* Lin.transferTo(0, in.size(), out);) Z2 R7 s% I# l% X( u1 P5 P- u
} finally {
% x1 |8 f% o6 @$ Eif (in != null)
# F. y. n. f$ j# I1 M9 Min.close();3 }) {0 S* U3 |. n
if (out != null)" z/ T+ S' \3 a9 @
out.close();
$ z6 ~0 s3 D* R F L5 z}
, V( O* o/ `6 i% @9 n; C! H}* H, e2 c7 U1 S. C7 N
}上面的代码中使用Java5中的NIO API,它能快速的完成任务
, x) E: l8 R: e: P# g |