- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.BufferedWriter;
- import com.xgh.util.P;
- /**
- * 题目:设计一个带缓冲流的文件复制类
- * @author xiaogh
- */
- public class CopyFileByBuffered {
-
- public static void main(String[] args){
-
- // File file1 = new File("E:\\音乐\\钢琴\\Maksim Mrvica - Hana's Eyes.mp3");
- File file1 = new File("F:\\others");
- File file2 = new File("H:\\培训后需要材料列表\\南航运行网截图");
- CopyFileUtil util = new CopyFileUtil();
- long start = System.currentTimeMillis();
- util.copyAll(file1, file2);
- P.rintln(System.currentTimeMillis() - start + "毫秒");
- }
- }
- class CopyFileUtil{
-
- /**
- * 可以copy文件及文件夹
- * @param sourceFile 源文件或者源文件夹
- * @param targetFile 目标文件夹
- */
- public void copyAll(File sourceFile, File targetFile){
-
- if(sourceFile.isFile()){
- copyFile(sourceFile, targetFile);
- }
- else{
- copyFolder(sourceFile, targetFile);
- }
- }
-
- //这个方法只能copy文件
- private void copyFile(File sourceFile, File targetFile){
-
- BufferedInputStream bis = null;
- BufferedOutputStream bos = null;
- BufferedWriter bw = null;
-
- try {
- bis = new BufferedInputStream(new FileInputStream(sourceFile));
- bos = new BufferedOutputStream(new FileOutputStream(targetFile.getAbsolutePath() + File.separator + sourceFile.getName()));
-
- //查看copy之后的文件位置
- String str = targetFile.getAbsolutePath() + File.separator + sourceFile.getName();
- P.rintln(str);
- File file = new File("D:\\copy.log");
- if(!file.exists()){
- file.createNewFile();
- }
-
- //将copy记录写入日志
- bw = new BufferedWriter(new FileWriter(file, true));
- bw.write(sourceFile.getAbsolutePath() + " --> " + str);
- bw.newLine();
- bw.flush();
-
- //copy文件
- byte[] bs = new byte[1024];
- int len = 0;
- while((len = bis.read(bs)) != -1){
- bos.write(bs, 0, len);
- bos.flush();
- }
-
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if(bis != null){
- try{
- bis.close();
- } catch(IOException ex){
- ex.printStackTrace();
- }
- }
- if(bos != null){
- try{
- bos.close();
- } catch(IOException ex){
- ex.printStackTrace();
- }
-
- }
- if(bw != null){
- try{
- bw.close();
- } catch (IOException ex){
- ex.printStackTrace();
- }
-
- }
- }
- }
-
- //copy文件和文件夹
- private void copyFolder(File sourceFile, File targetFile){
-
- //预先将文件夹创建
- File f = new File(targetFile.getAbsolutePath() + File.separator + sourceFile.getName());
- f.mkdir();
-
- File[] files = sourceFile.listFiles();
- for(File file : files){
- if(file.isFile()){
- copyFile(file, f);
- }
- else{
- copyFolder(file, f);
- }
- }
- }
- }
复制代码
这个是我看了题目试敲的。 |