import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
/*
* 根据文件目录复制源文件
* Arno 2016-07-15
*/
public class CopyCourseFile {
public static void main(String[] args) {
String catalogFile= "F:\\copyJavaFileDemo.txt"; // 导出文件目录文件
String outFileBasePath ="F:\\"; // 输出文件根目录
CopyCourseFile.readFileCopye(catalogFile, outFileBasePath);
}
/*
* 读取目录文件 copy目录中文件
* param catalogFile 目录文件路径只支持文本文件; outFileBasePath 输出文件根目录
*/
public static void readFileCopye(String catalogFile,String outFileBasePath){
try {
String courseFilePath = new File("").getCanonicalPath(); //获得工程路径
//本地工程名称
String projectName = courseFilePath.substring(courseFilePath.lastIndexOf("\\")+1, courseFilePath.length());
outFileBasePath = outFileBasePath +"\\"+ projectName;
BufferedReader br = new BufferedReader(new FileReader(catalogFile));//构造一个BufferedReader类来读取文件
String s = null;
int sum = 0; //复制文件数量
System.out.println(" copy ... ...");
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
if(s.indexOf(".") == -1){
System.err.println("无效的文件路径 已跳过 请确认目录中是否有漏掉文件! " + s);
continue;
}
boolean isSuccess = CopyCourseFile.copyFile(courseFilePath + "\\" + s,outFileBasePath + "\\" + s);
if(isSuccess){
sum ++;
System.out.println(outFileBasePath + "\\" + s);
}else{
System.err.println("复制中止出现上面错误! ");
break;
}
}
System.out.println("copy sum : " + sum);
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* 复制文件
* param oldPath 源文件; newPath 输出文件
*/
public static boolean copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
File newfile = new File(newPath);
if (oldfile.exists()) { //文件存在时
//判断目标文件所在的目录是否存在
if(!newfile.getParentFile().exists()) {
//如果目标文件所在的目录不存在,则创建父目录
if(!newfile.getParentFile().mkdirs()) {
System.err.println("创建目标文件所在目录失败 : " + newPath);
return false;
}
}
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1024];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
fs.write(buffer, 0, byteread);
}
inStream.close();
return true;
}else{
System.err.println("源文件不存在 : "+ oldPath);
return false;
}
} catch (Exception e) {
System.err.println("复制文件出错 : "+ oldPath + "-->" +newPath);
e.printStackTrace();
return false;
}
}
}