IO流

IO流体系

分类 字节输入流 字节输出流 字符输入流 字符输出流
抽象基类 InputStream OutputStream Reader Writer
访问文件 FileInputStream FileOutputStream FileReader FileWriter
访问数组 ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter
访问字符串 StringReader StringWriter
访问管道 PipedInputStream PipedOutputStream PipedReader PipedWriter
缓冲流 BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
转换流 InputStreamReader OutputStreamWriter
对象流 ObjectInputStream ObjectOutputStream
抽象基类 FilterInputStream FilterOutputStream
打印流 PrintStream PrintWriter
推回输入流 PushbackInputStream PushBackReader
特殊流 DataInputStream DataOutputStream

文件流

代码块

import java.io.File;

public class File01 {
	public static void main(String[] args) {
		String s = "D:/Users/MrXiaoK/Desktop/Java/JavaStudy/src/cn/xiaok/Io/1.txt";
		File file = new File(s);
		System.out.println("返回文件名 "+file.getName()); //String
		System.out.println("返回路径 "+file.getPath()); //String
		System.out.println("返回绝对路径 "+file.getAbsolutePath()); //String
		System.out.println("返回父路径 "+file.getParent()); //String
		System.out.println("返回父路径目录 "+file.getParentFile()); //File
		System.out.println("返回父路径目录名 "+file.getParentFile().getName()); //没有则报NullPointerException

	}
}
import java.io.File;

public class File02 {
	public static void main(String[] args) {
		String s = "D:/Users/MrXiaoK/Desktop/Java/JavaStudy/src/cn/xiaok/Io";
		File file = new File(s);
		System.out.println("是否存在   "+file.exists());  
		System.out.println("是否是文件   "+file.isFile());
		System.out.println("是否是文件夹   "+file.isDirectory());  //均为boolean

	}
}
import java.io.File;
import java.io.IOException;

public class File03 {
	public static void main(String[] args) throws IOException {
		String s = "D:/Users/MrXiaoK/Desktop/Java/JavaStudy/src/cn/xiaok/Io/1.txt";
		File file = new File(s);
		file.createNewFile();


		System.out.println("是否存在   "+file.exists());  
		System.out.println("是否是文件   "+file.isFile());
		System.out.println("是否是文件夹   "+file.isDirectory());


		file.delete();

		System.out.println("是否存在   "+file.exists());  
		System.out.println("是否是文件   "+file.isFile());
		System.out.println("是否是文件夹   "+file.isDirectory());  //均为boolean

	}
}
import java.io.File;
import java.io.IOException;

public class File04 {
	public static void main(String[] args) throws IOException {
		String s = "test";
		File file = new File(s);
		boolean a = file.mkdir();   //文件若不存在则创建 返回true  文件若存在则创建失败 返回false
		System.out.println(a);
		File files = new File("test01");
		boolean b = files.mkdirs(); //文件若不存在则创建 返回true  文件若存在也会创建 返回false
		System.out.println(b);

		System.out.println("-----------------------------");
		File fileone = new File("D:/test");
		String[] subNames = fileone.getAbsoluteFile().list();  //列出下级名称
		for (String string : subNames) {
			System.out.println(string);
		}

		System.out.println("--------------------------");
		File[] filetwo = fileone.getAbsoluteFile().listFiles();  //列出下级对象路径
		for (File file2 : filetwo) {
			System.out.println(file2);
		}

		System.out.println("------------------------");
		File[] fileThree = fileone.listRoots();   //列出所有盘符
		for(File fileThrees:fileThree) {
			System.out.println(fileThrees);
		}
	}
}
案例-计算文件夹大小
import java.io.File;
import java.io.IOException;

public class File05 {
	public static void main(String[] args) throws IOException {
		String p = "D:\\Users\\MrXiaoK\\Desktop\\Java\\JavaStudy";
		File src = new File(p);
		fileList(src,0);
		fileSize(src);
		System.out.println(count);
	}

	public static void fileList(File src,int i) {  //递归实现遍历文件夹
		for(int j=0;j<i;j++) {
			System.out.print("-");
		}
		System.out.println(src.getName());
		if(!src.exists() || src.isFile() ) {
			return;
		}else {
			if(src.isDirectory()) {
				for(File f:src.listFiles()) {
					fileList(f,i+1);
				}
			}
		}
	}
	static int count = 0;
	public static void fileSize(File src) {    //递归实现计算文件夹大小
		if(src.isFile()) {
			count += src.length();
			return;
		}else {
			for(File f:src.listFiles()) {
				fileSize(f);
			}
		}
	}
}

字符流

FileReader FileWriter

代码块

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

/**使用Reader Writer文件复制
 * @author MrXiaoK
 *
 */
public class File13 {

	public static void main(String[] args) {
		File in = new File("a.txt");
		File out = new File("abc.txt");
		Reader read = null;
		Writer write = null;
		try {
			read = new FileReader(in);
			write = new FileWriter(out);
			char[] ch = new char[5];
			int len = -1;
			while((len  = read.read(ch)) != -1) {
				write.write(ch, 0, len);
			}
			write.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch(IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(write!=null) write.close();
				if(read!=null) read.close();
			}catch(IOException e) {
				e.printStackTrace();
			}
		}

	}
}

字节流

FileInputStream FileOutputStream

代码块

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**文件拷贝
 * @author MrXiaoK
 *
 */
public class File11 {

	public static void main(String[] args) throws IOException {
		fileCopy("abc.txt","abcde.txt");
	}
	public static void fileCopy(String input,String output) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(input);
			out = new FileOutputStream(output);
			byte[] copy = new byte[5];
			int len = 0;
			while((len=in.read(copy))!=-1) {
				out.write(copy, 0, len);
			}
			out.flush();
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(out!=null)
					out.close();
				if(in!=null)
					in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

案例1-文件复制
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**文件拷贝
 * @author MrXiaoK
 *
 */
public class File11 {

	public static void main(String[] args) throws IOException {
		fileCopy("abc.txt","abcde.txt");
	}
	public static void fileCopy(String input,String output) {
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(input);
			out = new FileOutputStream(output);
			byte[] copy = new byte[5];
			int len = 0;
			while((len=in.read(copy))!=-1) {
				out.write(copy, 0, len);
			}
			out.flush();
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(out!=null)
					out.close();
				if(in!=null)
					in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
案例2-文件夹复制
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/** 文件夹复制
 * @author MrXiaoK
 *
 */
public class File12 {
	public static void main(String[] args) throws FileNotFoundException {
		File in = new File("D:/迅雷下载");
		File out = new File("D:/迅雷下载bak");
		fileCopy(in,out);
	}

	public static void fileCopy(File in, File out) {
		if (in.isFile()) {
			OutputStream outp = null;
			InputStream inp = null;
			//文件夹创建
			File temp = in.getParentFile();
			StringBuffer sb = new StringBuffer();
			while((temp.getName().length() !=0) && temp.getParentFile() != null) {
				sb.insert(0, "/"+temp.getName());
				temp = temp.getParentFile();
			}
			File t = new File(out.getAbsolutePath()+sb);
			t.mkdirs();
	
			File files = new File(t.getAbsolutePath()+"/"+in.getName());
			try {
				inp = new FileInputStream(in);
				outp = new FileOutputStream(files);
				byte[] copy = new byte[1024*200]; //200MB
				int len = 0;
				while ((len = inp.read(copy)) != -1) {
					outp.write(copy,0,len);
				}
				outp.flush();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				try {
					if(outp!=null) outp.close();
					if(inp!=null) inp.close();
				}catch(IOException e) {
					e.printStackTrace();
				}
			}
			return;
		}else if(in.isDirectory()) {
			for(File f:in.listFiles()) {
				fileCopy(f,out);
			}
		}
	}
}

字节数组流

字节数组输入流 ByteArrayInputStream

代码块

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/** 字节数组输入流
 * @author MrXiaoK
 *
 */
public class File14 {

	public static void main(String[] args) {
		byte[] dest = "hello world! auto MrXiaoK".getBytes();
		InputStream data = null;
		data = new ByteArrayInputStream(dest);
		byte[] newDest = new byte[5];
		int len = -1;
		try {
			while((len = data.read(newDest)) != -1) {
				String s = new String(newDest,0,len);
				System.out.println(s);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

字节数组输出流 ByteArrayOutputStream

代码块

import java.io.ByteArrayOutputStream;

/** 字节数组输出流
 * @author MrXiaoK
 *
 */
public class File15 {

	public static void main(String[] args) {
		String msg = "hello world! my name is MrXiaoK";
		byte[] dest = msg.getBytes();

		ByteArrayOutputStream outPut;
		outPut = new ByteArrayOutputStream();
		outPut.write(dest,0,dest.length);

		byte[] dests = outPut.toByteArray();
		System.out.println(dests.length+"--->"+new String(dests));
	}
}

案例-文件复制
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

/**使用Reader Writer文件复制
 * @author MrXiaoK
 *
 */
public class File13 {

	public static void main(String[] args) {
		File in = new File("a.txt");
		File out = new File("abc.txt");
		Reader read = null;
		Writer write = null;
		try {
			read = new FileReader(in);
			write = new FileWriter(out);
			char[] ch = new char[5];
			int len = -1;
			while((len  = read.read(ch)) != -1) {
				write.write(ch, 0, len);
			}
			write.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch(IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(write!=null) write.close();
				if(read!=null) read.close();
			}catch(IOException e) {
				e.printStackTrace();
			}
		}
	
	}
}

实现资源释放

try…with…resource

代码块

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/** try…with…resource
 * 实现资源释放
 * @author 20131
 *
 */
public class File17 {

	public static void main(String[] args) {
		try {
			copyFile(new FileInputStream("a.txt"),new FileOutputStream("aaa.txt"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	public static void copyFile(InputStream in,OutputStream out) {
		try(in;out){ //要更改eclipse jdk达到9以上
			byte[] bytes = new byte[5];
			int len = -1;
			while((len = in.read(bytes)) != -1) {
				out.write(bytes,0,len);
			}
			out.flush();
		} catch(FileNotFoundException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}

	}
}

字节缓冲流

BufferedInputStream BufferedOutStream

代码块

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/** 
 * 字节缓冲流-提升效率
 * @author MrXiaoK
 *
 */
public class File20 {

	public static void main(String[] args) {
		long t = System.currentTimeMillis();//获取当前时间
		System.out.println("使用字节缓冲前:");
		copy("D:/迅雷下载/jdk-10.0.2_windows-x64_bin.exe","D:/jdk-10.0.2_windows-x64_bin.exe");
		long t1 = System.currentTimeMillis();
		System.out.println(t1-t);
		System.out.println("使用字节缓冲后:");
		t = System.currentTimeMillis();
		bufCopy("D:/迅雷下载/jdk-10.0.2_windows-x64_bin.exe","D:/jdk-10.0.2_windows-x64_bin.exe");
		t1 = System.currentTimeMillis();
		System.out.println(t1-t);
	}
	public static void copy(String a,String b) {
		try(InputStream in = new FileInputStream(a);OutputStream out = new FileOutputStream(b)){
			byte[] flush = new byte[1024];
			int len = -1;
			while((len = in.read(flush))!= -1) {
				out.write(flush,0,len);
			}
			out.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void bufCopy(String a,String b) { //使用字节缓冲
		try(InputStream in = new BufferedInputStream(new FileInputStream(a));
				OutputStream out = new BufferedOutputStream(new FileOutputStream(b))){
			byte[] flush = new byte[1024];
			int len = -1;
			while((len = in.read(flush))!= -1) {
				out.write(flush,0,len);
			}
			out.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


字符缓冲流

BufferedReader BufferedWriter

代码块

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

/** 
 * 字符缓冲流-提升效率
 * @author MrXiaoK
 *增加逐行读取readLine
 *增加换行newLine
 */
public class File21 {

	public static void main(String[] args) {
//		long t = System.currentTimeMillis();//获取当前时间
//		System.out.println("使用字节缓冲前:");
//		copy("abc.txt","abc-copy1.txt");
//		long t1 = System.currentTimeMillis();
//		System.out.println(t1-t);

		System.out.println("使用字节缓冲后:");
		long t2 = System.currentTimeMillis();
		bufCopyLine("abc.txt","abc-copy2.txt");
//		bufCopy("abc.txt","abc-copy.txt");
		long t3 = System.currentTimeMillis();
		System.out.println(t3-t2);
	}
	//-------------------------------------------------------------------------------------
	public static void bufCopyLine(String a,String b) { //使用字符缓冲
		try(BufferedReader r = new BufferedReader(new FileReader(a));
				BufferedWriter w = new BufferedWriter(new FileWriter(b))){
			String line = null;
			while((line = r.readLine())!= null) { //逐行读取
				w.write(line); //逐行写入
				w.newLine(); //换行
			}
			w.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//-------------------------------------------------------------------------------------
	public static void copy(String a,String b) {
		try(Reader r = new FileReader(a);Writer w = new FileWriter(b)){
			char[] ch = new char[1024];
			int len = -1;
			while((len=r.read(ch)) != -1) {
				w.write(ch, 0, len);
			}
			w.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void bufCopy(String a,String b) { //使用字符缓冲
		try(BufferedReader r = new BufferedReader(new FileReader(a));
				BufferedWriter w = new BufferedWriter(new FileWriter(b))){
			char[] flush = new char[1024];
			int len = -1;
			while((len = r.read(flush))!= -1) {
				w.write(flush,0,len);
			}
			w.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

转换流

InputStreamReader OutputStreamWriter

以字符流的形式操作字节流(纯文本的)

指定字符集

字节流转字符流

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;

/**
 * 转换流: InputStreamReader OutputStreamWriter
 * 1、以字符流的形式操作字节流(纯文本的)
 * 2、指定字符集
 * 字节流转字符流
 * @author MrXiaoK
 *
 */
public class File22 {

	public static void main(String[] args) throws IOException {

		//操作System.in 和 System.out
		try(BufferedReader inr = new BufferedReader(new InputStreamReader(System.in));
				BufferedWriter outw = new BufferedWriter(new OutputStreamWriter(System.out))) {
			String msg = "";
			while(true) {
				msg = inr.readLine();
				if(msg.equals("exit")) break;
				outw.write(msg);
				outw.newLine();
				outw.flush();
			}
		}
		//操作网络流  下载百度的源代码
		try(BufferedReader inr = new BufferedReader(new InputStreamReader(new URL("http://www.baidu.com").openStream(),"UTF-8"));
				BufferedWriter outw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("baidu.html"),"UTF-8"))){
			String msg = "";
			while((msg = inr.readLine())!=null) {
				outw.write(msg);
				outw.newLine();
			}
			outw.flush();
		}
	}
}

对象流

ObjectOutputStream ObjectInputStream

代码

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/** 对象流
 * ObjectOutputStream ObjectInputStream
 * 1、写出后读取
 * 2、读取的顺序与写出保持一致
 * 3、不是所有的对象都可以序列化Serializable
 * @author MrXiaoK
 *
 */
public class File23 {

	public static void main(String[] args) throws IOException {
		ObjectOutputStream ous = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("obj.txt")));
		ous.write(123);
		ous.writeChar('a');
		ous.writeObject(new Person("张三",25));
		ous.flush();
		ous.close();

		ObjectInputStream  ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("obj.txt")));
		Object objInt = ois.read();
		Object objChar = ois.readChar();
		Object obj = null;
		try {
			obj = ois.readObject();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		if(objInt instanceof Integer) {
			int i = (int) objInt;
			System.out.println(i);
		}
		if(objChar instanceof Character) {
			char c = (char) objChar;
			System.out.println(c);
		}
		if(obj instanceof Person) {
			Person p = (Person)obj;
			System.out.println(p);
		}
	}

}
class Person implements Serializable{  //
	private String name;
	private int age;
	public Person(){

	}
	public Person(String name,int age) {
		this.name = name;
		this.age = age;
	}
	public String toString() {
		return "name:"+name+",age:"+age;
	}
}

打印流

PrintStream

代码块

import java.io.BufferedOutputStream;

import java.io.FileDescriptor;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.PrintStream;



/** 

 * 打印流

 * @author MrXiaoK

 *

 */

public class File25 {



    public static void main(String[] args) throws IOException {

        PrintStream ps = System.out;

        ps.print(false);  

        ps.print("打印出。。。。");

  

        ps = new PrintStream(new BufferedOutputStream(new FileOutputStream("print.txt")),true); //取代flush

        ps.print(true);

        ps.print("打印到文件内。。。。");

//        ps.flush();

  

        //重定向输出端

        System.setOut(ps);

        System.out.println("从打印到控制台转为打印到文件内");

  

        //重定向会输出端为控制台

        System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)),true));

        System.out.println("回到控制台输出");

    }

  

}

文件分割

RandomAccessFile

随机读取

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/** 
 * 文件分割输出
 * @author MrXiaoK
 *
 */
public class File26 {

	public static void main(String[] args) throws IOException {
		File file = new File("src/cn/xiaok/Io/File20.java");
		long len = file.length();
		int size = 1024; //分块大小
		int block = (int)Math.ceil(len*1.0/size); //分块数量
		int begin = 0; //起始位置
		int actualSize = (int)(len > size ? size:len); //结束位置
		for(int i=0;i<block;i++) {
			begin = i*actualSize;
				len -= size;
			System.out.println("--------------------第"+i+"块----------------------------------------------");
			test2(file,begin,actualSize);
		}
	}
	public static void test1() throws IOException {
		RandomAccessFile raf = new RandomAccessFile(new File("src/cn/xiaok/Io/File25.java"),"r");
		raf.seek(2); //从第二字节开始
		byte[] flush = new byte[1024];
		int len = -1;
		while((len = raf.read(flush)) != -1) {
			System.out.println(new String(flush,0,len));
		}
		raf.close();
	}
	/**文件分块
	 * @param file
	 * @param begin 起始位置
	 * @param end   结束位置
	 * @throws IOException
	 */
	public static void test2(File file,int begin,int end) throws IOException {
		RandomAccessFile raf = new RandomAccessFile(file,"r");
		raf.seek(begin);
		byte[] flush = new byte[1024];
		int len = -1;
		while((len = raf.read(flush)) != -1) {
			if(end > len) {
				System.out.println(new String(flush,0,len));
				end -= len;
			}else {
				System.out.println(new String(flush,0,end));
				break;
			}
		}
		raf.close();
	}
	
}

文件拆分及其合并

SequenceInputStream

package cn.xiaok.Io;

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.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 *    文件拆分 与 文件合并
 * 
 * @author MrXiaoK
 *
 */
public class SplitFile {
	private File destPath;
	private File destDir;
	private int beginSize;
	private int Size;
	private List<File> fileList;

	public SplitFile(File destPath, File destDir, int beginSize, int Size) throws IOException {
		this.destPath = destPath;
		this.destDir = destDir;
		this.beginSize = beginSize;
		this.Size = Size;
		init();
	}

	/** 初始化
	 * @throws IOException
	 */
	private void init() throws IOException {
		long len = destPath.length();
		int num = (int) Math.ceil(len * 1.0 / Size);
		fileList = new ArrayList<>();
		for (int i = 0; i < num; i++) {
			if (i == num - 1)
				Size = (int) len;
			fileList.add(new File(destDir + "/" + i + "-" + destPath.getName()));
			split(i);
			beginSize += Size;
		}
	}

	/** 文件拆分
	 * @param i
	 * @throws IOException
	 */
	private void split(int i) throws IOException {
		RandomAccessFile raf1 = new RandomAccessFile(destPath, "r");
		RandomAccessFile raf2 = new RandomAccessFile(fileList.get(i), "rw");
		raf1.seek(beginSize);
		int lenth = -1;
		byte[] flush = new byte[1024];
		while ((lenth = raf1.read(flush)) != -1) {
			if (Size > lenth) {
				raf2.write(flush, 0, lenth);
				Size -= lenth;
			} else {
				raf2.write(flush, 0, Size);
				break;
			}
		}
		raf2.close();
		raf1.close();
	}
	/** 文件合并
	 * SequenceInputStream 实现输入流的集合
	 * @param file
	 * @throws IOException
	 */
	public void mergeFile(File file) throws IOException {
		OutputStream os = new BufferedOutputStream(new FileOutputStream(file,true));
		Vector<InputStream> vi = new Vector<>();
		SequenceInputStream sis = null;
		for(int i=0;i<fileList.size();i++) {
			vi.add(new BufferedInputStream(new FileInputStream(fileList.get(i))));
		}
		sis = new SequenceInputStream(vi.elements());
		byte[] flush = new byte[1024];
		int len =-1;
		while((len=sis.read(flush))!=-1) {
			os.write(flush,0,len);
		}
		os.flush();
		sis.close();
		os.close();
		
	}
	public void mergeFile2(File file) {
		for(int i=0;i<fileList.size();i++) {
			try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileList.get(i)));
					BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file,true))){
				byte[] flush = new byte[1024];
				int len = -1;
				while((len = bis.read(flush))!=-1) {
					bos.write(flush, 0, len);
				}
				bos.flush();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
	public static void main(String[] args) throws IOException {
			SplitFile sf = new SplitFile(new File("src/cn/xiaok/Io/SplitFile.java"), new File("dest"), 0, 1024);
			sf.mergeFile(new File("dest/mergeFile.java"));
	}
}

posted @ 2020-04-02 16:58  MrXiaoK  阅读(88)  评论(0)    收藏  举报