| package com.itheima; import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.text.DecimalFormat;
 public class Test7 {
 /**第七题
 * 使用带缓冲功能的字节流复制文件。
 * @param args
 */
 public static void main(String[] args){
 System.out.println("使用前请修改main文件中的复制的文件的路径和拷贝到
 
 得路径");
 //要复制的文件
 String copyFile = "E:\\eg.txt";
 //拷贝到得路径
 String savePath = "F:\\";
 //调用复制文件的函数,传入要复制文件的路径和目标文件的路径
 copyFile(copyFile, savePath);
 }
 private static void copyFile(String copyFile, String savePath) {
 //声明输入流
 BufferedInputStream bis = null;
 //声明输出流
 BufferedOutputStream bos = null;
 try {
 //声明并创建一个复制文件对象
 File File = new File(copyFile);
 //声明并创建一个保存文件对象
 File Path = new File(savePath);
 // 如果要复制的文件不存在或者不是文件,发出提示并退出程序
 if ((File.exists() == false) || File.isFile() == false) {
 System.out.println("无效的文件,请检查");
 System.exit(0);
 }
 // 如果要保存的目录不存在,则创建该目录
 if (Path.isDirectory() == false) {
 System.out.println("你指定的目录不存在,将自动创建。");
 Path.mkdirs();
 }
 // 创建目标文件完整路径
 File saveFile = new File(savePath + "\\" + File.getName());
 // 如果saveFile 是一个文件,说明有同名文件存在,则提示并退出程序,避免覆
 
 盖同名文件
 if (saveFile.isFile()) {
 System.out.println("注意!该目录下有同名文件。");
 System.out.println(0);
 }
 // 创建输入流和输出流
 bis = new BufferedInputStream(new FileInputStream(copyFile));
 bos = new BufferedOutputStream(new FileOutputStream(saveFile));
 // 获取输入流中的字节数
 long len = bis.available();
 // 格式化显示文件大小,保留1位小数
 DecimalFormat df = new DecimalFormat(".0");
 String size = null;
 if (len > 1024 * 1024 * 200) {
 System.out.println("要复制的文件超过200MB,不能复制。");
 } else if (len > 1024) {
 size = df.format(len / 1024) + "MB";
 } else {
 //计算出文件的大小
 size = len + "字节";
 }
 System.out.println("文件大小:" + size);
 System.out.println("复制中...");
 // 如果文件大于200MB,用一次读一个字节方式
 // 否则就用数组一次性读取方式复制
 if (len > 1024 * 1024 * 200) {
 int by;
 while ((by = bis.read()) != -1) {
 bos.write(by);
 }
 } else {
 // 创建数组缓冲区,指定大小为输入流中的字节数len
 byte[] bytes = new byte[(int) len];
 bis.read(bytes);
 bos.write(bytes); // 将数组中的所有数据写入的输出流缓冲区中。
 }
 System.out.println("复制完成");
 }
 //抛出文件复制失败异常
 catch (Exception e) {
 throw new RuntimeException("复制文件失败");
 }
 //关闭所有流
 finally
 {
 try {
 if (bis != null)
 {
 //关闭输入流
 bis.close();
 }
 if (bos != null)
 {
 //关闭输出流
 bos.close();
 }
 }
 catch (IOException e)
 {
 throw new RuntimeException("输出流关闭失败");
 }
 }
 }
 }
 |