11.练习

    技术2022-07-13  80

    11.练习_文件拆分和合并

    学习:第7遍


    1.练习:文件拆分和合并 将"c:/aaa/src.zip"20M大小的文件拆分成每6M为一个小文件 src.zip_1 src.zip_2 src.zip_3 src.zip_4


    //将"c:/aaa/src.zip"20M大小的文件拆分成每6M为一个小文件 //src.zip_1 //src.zip_2 //src.zip_3 //src.zip_4 public class TestStream { public static void main(String[] args) { String filePath="c:/aaa/src.zip"; splitFile(filePath); mergeFile(filePath+"_2"); } // 拆分文件:一个输入流,多个输出流 public static void splitFile(String filePath) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(filePath); // 每次读取6M byte[] buffer = new byte[1024 * 1024 * 6]; int num = -1; int index = 0; while ((num = fis.read(buffer)) != -1) { fos = new FileOutputStream(filePath + "_" + (++index)); fos.write(buffer, 0, num); fos.flush(); fos.close(); } System.out.println("拆分成功,共拆分为:" + index + "个"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } // 合并文件:一个输出流,多个输入流,把当前_之前所有一致的 public static void mergeFile(String filePath) { //截取_之前的文件路径 String basePath = filePath.substring(0, filePath.lastIndexOf("_")); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(basePath); int index = 1; File file = null; //如果basePath_index文件对象存在就输入 while ((file = new File(basePath + "_" + index++)).exists()) { fis = new FileInputStream(file); /** * 方法:fis.available() * 作用:返回可读字节数 */ byte[] buffer = new byte[fis.available()]; //数据读到buffer中 fis.read(buffer); fos.write(buffer); fos.flush(); fis.close(); } System.out.println("合并成功:"+basePath); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
    Processed: 0.019, SQL: 9