public static void main(String[] args) {
// TODO Auto-generated method stub
//测试拷贝文件
String fromFile="F:/fieCopyTest/fromFile.xlsx";//fromFile.xlsx
String toFile="F:/fieCopyTest/toFile.xlsx";
try {
copyFile(fromFile,toFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void copyFile(String fromFileName,String toFileName) throws Exception{
File fromFile = new File(fromFileName);
File toFile = new File(toFileName);
//源文件不存在
if(!fromFile.exists()){
throw new Exception("FileCopy:"+"no such source file"+fromFileName);
}
//源文件不是合法文件
if(!fromFile.isFile()){
throw new Exception("FileCopy:"+"can't copy file"+fromFileName);
}
//源文件不能读取
if(!fromFile.canRead()){
throw new Exception("FileCopy:"+"can't Read file"+fromFileName);
}
//是否是目录文件
if(toFile.isDirectory()){
toFile = new File(toFile,fromFile.getName());
}
//目的文件是否存在
if(toFile.exists()){
//toFile不能读写
if(!toFile.canWrite()){
throw new Exception("fileCopy:"+"can not Write"+toFileName);
//System.out.print("OverWrite exiting file "+toFileName+"?(Y/N):");
//System.out.flush();
}else{
String parent = toFile.getParent();
if(parent ==null){
parent = System.getProperty("user.dir");
}
File dir = new File(parent);
if(!dir.exists()){
throw new Exception("fileCopy:"+"destination directory doesn't exist"+dir.getName());
}
if(!dir.isFile()){
throw new Exception("fileCopy:"+"destination is not a file"+dir.getName());
}
if(!dir.canWrite()){
throw new Exception("fileCopy:"+"destination can't to be write"+dir.getName());
}
}
}
FileInputStream from = null;
FileOutputStream in =null;
from = new FileInputStream(fromFile);
in = new FileOutputStream(toFile);
byte[] buffer = new byte[4096];
int byteRead;
//write 方式一,将文件读入字节流,可以读写 xlsx,xls,doc ,docx,txt等文件
while((byteRead=from.read(buffer))!=-1){
in.write(buffer,0,byteRead);//开始write操作
}
//write 方式二,直接读取文件,可以读写txt文件
from.close();
in.close();
}