之前看到网上很多文件copy的文章,可能本人技术有限,拿过来直接用的话,都会出IO异常,经过一个多小时的研究,现在将完整的 copy文件的代码 贴出来,保证可用
假如想把data/video/xxx.mp4这个路径下的文件复制到 data/oss/下 那么首先我们要新建一个oss的文件夹 代码如下:
//创建文件夹
//参数就是创建文件夹的路径地址,data/oss
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {// 判断目录是否存在
System.out.println("创建目录失败,目标目录已存在!");
return false;
}
if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
destDirName = destDirName + File.separator;
}
if (dir.mkdirs()) {// 创建目标目录
System.out.println("创建目录成功!" + destDirName);
return true;
} else {
System.out.println("创建目录失败!");
return false;
}
}
文件夹创建成功之后,我们就要copyFile了
/**
* 复制单个文件
* @param oldPath String 原文件路径 如:data/video/xxx.mp4
* @param newPath String 复制后路径 如:data/oss/xxx.mp4
* @return boolean
*/
public void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
File newFile = new File(newPath);
if (!newFile.exists()){
newFile.createNewFile();
}
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
以上两个方法就可以任意的复制文件到任意路径,当然这个是单个的文件,多个文件的话,很多博客里面都有,有需要的可以看一下.