java中实现复制文件和文件夹

时间:2022-01-18 21:35:39

java中实现复制文件和文件夹

public static void copyFile(File sourceFile,File targetFile)

throws IOException{

// 新建文件输入流并对它进行缓冲

FileInputStream input = new FileInputStream(sourceFile);

BufferedInputStream inBuff=new BufferedInputStream(input);

// 新建文件输出流并对它进行缓冲

FileOutputStream output = new FileOutputStream(targetFile);

BufferedOutputStream outBuff=new BufferedOutputStream(output);

// 缓冲数组

byte[] b = new byte[1024 * 5];

int len;

while ((len =inBuff.read(b)) != -1) {

outBuff.write(b, 0, len);

}

// 刷新此缓冲的输出流

outBuff.flush();

//关闭流

inBuff.close();

outBuff.close();

output.close();

input.close();

}