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

java 文件拷贝操作

2014-04-09 13:31 281 查看
package com.hqlh.util;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

/**

* file copy operate

*

* @author jiapengxun

*

*/

public class FileOperateUtil {

/**

* 复制整个文件夹内容

*

* @param oldPath

* String 原文件路径 如:c:/fqf

* @param newPath

* String 复制后路径 如:f:/fqf/ff

* @return boolean

*/

public static void copyFolder(String oldpath, String newPath) {

try {

// 如果文件夹不存在 则建立新文件夹

(new File(newPath)).mkdirs();

File file = new File(oldpath);

String[] files = file.list();

File temp = null;

for (int i = 0; i < files.length; i++) {

if (oldpath.endsWith(File.separator)) {

temp = new File(oldpath + files[i]);

} else {

temp = new File(oldpath + File.separator + files[i]);

}

if (temp.isFile()) {

FileInputStream input = new FileInputStream(temp);

FileOutputStream output = new FileOutputStream(newPath + "/" + temp.getName().toString());

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

int len;

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

output.write(b, 0, len);

}

output.flush();

output.close();

input.close();

}

// 如果是子文件夹

if (temp.isDirectory()) {

copyFolder(oldpath + "/" + files[i], newPath + "/"

+ files[i]);

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 复制单个文件

*

* @param oldPath

* String 原文件路径 如:c:/fqf.txt

* @param newPath

* String 复制后路径 如:f:/fqf.txt

* @return boolean

*/

public static void copyFile(String oldPath, String newPath) {

try {

int bytesum = 0;

int byteread = 0;

File oldfile = new File(oldPath);

if (!oldfile.exists()) { // 文件不存在时

FileInputStream inStream = new FileInputStream(oldPath); // 读入原文件

byte[] buffer = new byte[1444];

while ((byteread = inStream.read(buffer)) != -1) {

bytesum += byteread; // 字节数 文件大小

new FileOutputStream(newPath).write(buffer, 0, byteread);

}

inStream.close();

}

} catch (Exception e) {

e.printStackTrace();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: