复制文件代码实现,我这样的代码质量怎样?package copy_file;import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class CopyFile3 {
public static void main(String[] args) {
File a=new File("C:\\红楼梦_英文版.txt");
File b=new File("C:\\红楼梦_英文版 - 副 本.txt");
System.out.println(a.exists());
System.out.println(b.exists());
System.out.println("操作结果:"+ copyFile(a, b) );
} public static boolean copyFile(File a, File b){
boolean flag=false ;
if ( !a.exists() || !b.exists() ){
flag=false ;
return flag;
}
FileInputStream fis=null;
FileOutputStream fos=null;
int count =0;
byte [] by=new byte[1024];
try {
fis=new FileInputStream(a);
fos=new FileOutputStream(b);
for ( ; (count=fis.read(by) ) !=-1; ){
fos.write(by, 0, count);
}
flag=true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
}
文件复制代码实现
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class CopyFile3 {
public static void main(String[] args) {
File a=new File("C:\\红楼梦_英文版.txt");
File b=new File("C:\\红楼梦_英文版 - 副 本.txt");
System.out.println(a.exists());
System.out.println(b.exists());
System.out.println("操作结果:"+ copyFile(a, b) );
} public static boolean copyFile(File a, File b){
boolean flag=false ;
if ( !a.exists() || !b.exists() ){
flag=false ;
return flag;
}
FileInputStream fis=null;
FileOutputStream fos=null;
int count =0;
byte [] by=new byte[1024];
try {
fis=new FileInputStream(a);
fos=new FileOutputStream(b);
for ( ; (count=fis.read(by) ) !=-1; ){
fos.write(by, 0, count);
}
flag=true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
}
文件复制代码实现
FileChannel rc = new FileInputStream(new File("c:/test.txt")).getChannel();
rc.transferTo(0, rc.size(), new FileOutputStream(new File("c:/t2.txt")).getChannel());
rc.close();
你这个干什么用的
exists() 是干什么的;
感觉还行;
1 出IOE了以后,flag = true,复制成功??!!
2 判断目标文件是否存在,多此一举!
做的好的不光不该因为目标文件不存在而报错,反而应该很贴心的把不存在的目标文件夹一并建立。
另外,按照现在两个都需要存在的判断,判断成功以后FNFE那个catch,我没想明白怎么进去
3 1024的缓冲,貌似小了点
对比我的程序给你两点建议把,
首先副本文件应该是原文件-副本
所以这样副本文件名应该是自己生成的,而不是手动敲入的。
另外复制出现了问题,想看信息报错最好还是在log里面,所以输出信息最好还是放到log里面,log输出放到赋值的方法里面。
实现一种主函数只需要输入一个参数和方法就可以调用的效果是最好的。