将一个文件复制到另一个指定目录下,并比较复制后的两文件的大小是否相等,若相等表示复制成功。
这里以D盘的Hello.txt文件为例,复制到F盘根目录下。
代码如下:
package com.File;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/*
* 将一文件复制到指定路径下(这里以D盘的"Hello.txt"为例,文件大小为40字节)
* 并比较两个文件的字节大小是否相等,若两个文件字节大小相等,表示复制成功
*/
public class copy_File{
public static void main(String[] args) {
fileCopy("D:\\Hello.txt","F:\\");
}
//定义文件复制的方法
public static void fileCopy(String srcPath,String destPath){
int indx = srcPath.lastIndexOf("\\"); //获取出现"\\"的索引
String fileName = srcPath.substring(indx); //获取整个文件名(包括后缀)
File srcFile = new File(srcPath);
File destFile = new File(destPath+File.separator+fileName);
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(srcFile);
output = new FileOutputStream(destFile);
int length; //定义读取的长度
byte[] bytes = new byte[1024]; //每次读取到的字节存放在字节数组bytes中
while( (length = input.read(bytes)) != -1){ //-1表示读到最末尾了
output.write(bytes, 0, length); //表示在bytes数组中,输出从0号位置到length位的字符
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
finally{
try {
input.close(); //关闭输入流
output.close(); //关闭输出流
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
编译通过后,可在F盘根目录下找到Hello.txt文件,文件复制成功。
如有不妥之处,还望大家指正,谢谢!