您的位置:首页 > 编程语言 > Java开发

java基础之文件(夹)复制到另一个文件夹

2017-02-23 19:14 369 查看

文件或文件夹复制到另一个文件夹

public class FileCopy {
public static void main(String[] args) {
File sourceFile = new File("e:\\javaIO");
File targetFile = new File("e:\\javaFile");// 目标文件
System.out.println("共复制以下文件!");
copyDirectory(sourceFile, targetFile);
}
private static void copyDirectory(File sourceFile, File targetFile) {
if (sourceFile.isFile()) {// 如果是文件,则直接复制
copyFile(sourceFile, new File(targetFile, sourceFile.getName()));
System.out.println(sourceFile.getName()+"拷贝完成");
} else {//如果是目录,则遍历
File file = new File(targetFile, sourceFile.getName());//创建子文件夹
file.mkdirs();
System.out.println(file.getName()+"目录创建完成!");
File[] files = sourceFile.listFiles();
for (File file2 : files) {
copyDirectory(file2, file);
}
}
}


=================copyFile方法========================

方法一:用RandomAccessFile

private static void copyFile(File sourceFile, File targetDir) {
// TODO Auto-generated method stub
RandomAccessFile rafSource = null;
RandomAccessFile rafTarget =null;
try {
rafSource = new RandomAccessFile(sourceFile, "r");
rafTarget = new RandomAccessFile(targetDir, "rw");
rafTarget.setLength(sourceFile.length());
byte[] buff = new byte[1024*4];
int length = 0;
while((length=rafSource.read(buff)) != -1){
rafTarget.write(buff, 0, length);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
IOUtils.closeRandomAccessFile(rafTarget);
IOUtils.closeRandomAccessFile(rafSource);
}
}


方法二 IO流

public static void copyFile(File sourceFile, File targetFile) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFile));
bos = new BufferedOutputStream(new FileOutputStream(targetFile));
byte[] buff = new byte[1024];
int length;
while (-1 != (length = bis.read(buff))) {
bos.write(buff, 0, length);
}
bos.flush();
} catch (FileNotFoundException e) {
System.out.println("路径不存在");
System.exit(-1);
} catch (IOException e) {
System.out.println("文件读写错误");
System.exit(-1);
} finally {
IOUtils.closeInputStream(bis);
IOUtils.closeOutputStream(bos);
}
}
}


IOUtils工具类…..
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  文件拷贝 java基础