欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

IO流拆分以及合并文件

程序员文章站 2022-12-20 13:51:51
IO流拆分以及合并文件import java.io.*;import java.util.Enumeration;import java.util.Vector;public class Demo9 { public static void main(String[] args) { spiltFile(); MergeFile(); } private static void MergeFile() {//合并文件 File...

IO流拆分以及合并文件

import java.io.*; import java.util.Enumeration; import java.util.Vector; public class Demo9 { public static void main(String[] args) { spiltFile(); MergeFile(); } private static void MergeFile() {//合并文件 FileInputStream fileInputStream=null; SequenceInputStream sequenceInputStream=null; FileOutputStream fileOutputStream=null; try { File file=new File("D:\\Temp","合集.mp3"); fileOutputStream =new FileOutputStream(file); Vector<FileInputStream> vector=new Vector<>(); for (int i = 1; i <=5 ; i++) { File file1=new File("D:\\Temp",i+".mp3"); fileInputStream=new FileInputStream(file1); vector.add(fileInputStream); } Enumeration<FileInputStream> elements = vector.elements(); sequenceInputStream=new SequenceInputStream(elements); int len=0; byte[] bytes=new byte[1024*8]; while ((len=sequenceInputStream.read(bytes))!=-1){ fileOutputStream.write(bytes,0,len); fileOutputStream.flush(); } }catch (Exception e){ e.printStackTrace(); }finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (sequenceInputStream != null) { try { sequenceInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (fileInputStream!= null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static void spiltFile() {//拆分文件 RandomAccessFile in=null; RandomAccessFile out=null; RandomAccessFile out1=null; try{ File file=new File("C:\\Users\\Administrator\\Desktop\\mp3\\许巍 - 蓝莲花.mp3"); in=new RandomAccessFile(file,"rw"); //System.out.println(file.length()); long ls = file.length() /(1024*1024); for (int i = 1; i <=ls ; i++) { File file1=new File("D:\\temp",i+".mp3"); out=new RandomAccessFile(file1,"rw"); byte[] bytes=new byte[1024*1024]; in.read(bytes); out.write(bytes,0,1024*1024); in.seek(in.getFilePointer()); } File file2=new File("D:\\temp",ls+1+".mp3"); out1=new RandomAccessFile(file2,"rw"); int len=0; byte[] bytes=new byte[1024*8]; while ((len=in.read(bytes))!=-1){ out1.write(bytes,0,len); } }catch (Exception e){ e.printStackTrace(); }finally { if (out1 != null) { try { out1.close(); } catch (IOException e) { e.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } } 

本文地址:https://blog.csdn.net/qq_48967079/article/details/108025663

相关标签: IO流