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

java复制File文件操作

2013-09-25 13:00 381 查看
==========================复制File操作=========================

/**
*
* @param newPath要赋值的路径
* @param newName新文件名称
* @param oldPath 旧文件路径
* @return error 或者newPath + "/"+newName
*/
@SuppressWarnings("unused")
public static String complyFile(String newPath,String newName,String oldPath){
//String newPath = "WebRoot/WEB-INF/1";// 复制的新路径
//String oldPath = "WebRoot/WEB-INF/ebusiness.db";// 旧文件
try {

File file = new File(oldPath);

int bytesum = 0;
int byteread = 0;
if (file.exists()) { // 文件存在时
// 创建文件夹
File file2 = new File(newPath);
if (!file2.exists()) {
// 创建文件夹
file2.mkdirs();
}

File fileName = new File(newPath + "/"+newName);//新文件名和路径
if(!fileName.exists()){//如果文件不存在
fileName.createNewFile();
FileUtils.copyFile(file,fileName);//fileName文件名,file要复制的文件
}

//以下的方法是使用流的方式复制,这种方式有时会损坏文件
/*InputStream inStream = new FileInputStream(file); // 读入原文件
FileOutputStream fs = new FileOutputStream(newPath + "/"+newName); // 复制文件
byte[] buffer = new byte[1444];
System.out.println(inStream.read(buffer));
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();*/

} else {
System.out.println("文件不存在");
return "error";
}
} catch (Exception e) {
e.printStackTrace();
return "error";
}
return newPath + "/"+newName;

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