62,614
社区成员
发帖
与我相关
我的任务
分享
public static void copyFile(String fileName1,String fileName2) throws IOException {
File file1 = new File(fileName1);//待拷贝文件
File file2 = new File(fileName2);//生成文件
FileInputStream fileStream = new FileInputStream(file1);
FileOutputStream fileOutStream = new FileOutputStream(file2);
//byte[] byteArray = new byte[(int)file1.length()];适合小文件拷贝速度快占用内存大。
//fileStream.read(byteArray);
byte[] byteArray = new byte[1024];//通用文件拷贝速度慢
int temp = 0;
while((temp = fileStream.read(byteArray))!=-1){
System.out.println(temp);
fileOutStream.write(byteArray,0,temp);
}
fileStream.close();
fileOutStream.close();
}
复制方法改一下,上面的太丑陋了。
public static void copyFile(String fileName1,String fileName2) throws IOException {
File file1 = new File(fileName1);//待拷贝文件
File file2 = new File(fileName2);//生成文件
FileInputStream fileStream = new FileInputStream(file1);
FileOutputStream fileOutStream = new FileOutputStream(file2);
//byte[] byteArray = new byte[(int)file1.length()];适合小文件拷贝速度快占用内存大。
//fileStream.read(byteArray);
byte[] byteArray = new byte[1024];//通用文件拷贝速度慢
int temp = 0;
int count = 0;
while((temp = fileStream.read())!= -1){
if(count !=1024 ){
byteArray[count] = (byte)temp;
count ++;
} else{
count = 0;
fileOutStream.write(byteArray);
}
}
if(count != 0){
fileOutStream.write(byteArray, 0, count);
}
fileStream.close();
fileOutStream.close();
}
public static void main(String[] args) throws IOException {
copyFile("D:" + File.separator + "hello.txt","D:" + File.separator + "abc.txt");//调用四次该方法即可实现复制文件,不用重复四遍相同代码来复制四个文件
}