JavaIO总结

Java IO流分为字节流和字符流

下面首先介绍一下字节流

/**
 * 字节流测试
 * @author hc
 *
 */
public class Test {
	
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		createFile();
		inputStre();
		buffer();
		ObjectOutputstr();
	}
	public static void  createFile() throws IOException{
		
		//File file=new File("a.txt");
		//file.createNewFile();
		//创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。 
		File file2=new File("a/b/c");
		file2.mkdirs();
	}
	//字节流 inputstream
	//用来统计长度
	public  static void inputStre(){
		InputStream inputStream=null;
		try{
			int count=0;
			inputStream=new FileInputStream(new File("a.txt"));
			while(inputStream.read()!=-1){
				count++;
			}
			System.out.println("字符串长度是"+count+"字节");
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	/**
	 * FileOutputStream 循序渐进版, InputStream是所有字节输出流的父类,
	 * 子类有ByteArrayOutputStream,FileOutputStream,ObjectOutputStreanm,
	 * 这些我们在后面都会一一说到。先说FileOutputStream
	 * 缓冲区的使用
	 * @throws IOException 
	 */
	
	public static void buffer() throws IOException{
		byte[] buffer=new byte[1024];
		int num=0;
		FileInputStream fileInputStream=new FileInputStream(new File("a.txt"));
		FileOutputStream fileOutputStream=new FileOutputStream(new File("b.txt"));
		while ((num=fileInputStream.read(buffer))!=-1) {
			fileOutputStream.write(buffer, 0, num);
			
		}
		System.out.println("复制完成");
	}
	/**
	 * 读写对象
	 * ObjectInputStream 和ObjectOutputStream ,该流允许读取或写入用户自定义的类,
	 * 但是要实现这种功能,
	 * 被读取和写入的类必须实现Serializable接口,其实该接口并没有什么方法,可能相当于一个标记而已,但是确实不合缺少的
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @throws ClassNotFoundException 
	 */
	public static void ObjectOutputstr() throws FileNotFoundException, IOException, ClassNotFoundException{
		ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream(new File("o.txt")));
		ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream(new File("o.txt")));
		//将对象写到文件中
		objectOutputStream.writeObject(new Person(11, "张三"));
		 Object ob=   objectInputStream.readObject();
		 Person p=(Person)ob;
		 System.out.println(p.getName()+"---------"+p.getAge());
	}
	
	/*
	 * 
	 *.有时没有必要存储整个对象的信息,而只是要存储一个对象的成员数据,
	 *成员数据的类型假设都是Java的基本数据类型,这样的需求不必使用到与Object输入、输出相关的流对象,
	 *可以使用DataInputStream、DataOutputStream来写入或读出数据。
	 *
	 */
	/*
	 * PushbackInputStream类继承了FilterInputStream类是iputStream类的修饰者。提供可以将数据插入到输入流前端的能力(当然也可以做其他操作)。
	 * 简而言之PushbackInputStream类的作用就是能够在读取缓冲区的时候提前知道下一个字节是什么,
	 * 其实质是读取到下一个字符后回退的做法,这之间可以进行很多操作,
	 * 这有点向你把读取缓冲区的过程当成一个数组的遍历,遍历到某个字符的时候可以进行的操作,
	 * 当然,如果要插入,能够插入的最大字节数是与推回缓冲区的大小相关的,插入字符肯定不能大于缓冲区吧!
	 */
	public static void pushbackinputStream() throws IOException{
		  String str = "hello,rollenholt";  
		    PushbackInputStream push = null; // 声明回退流对象  
		    ByteArrayInputStream bat = null; // 声明字节数组流对象  
		    bat = new ByteArrayInputStream(str.getBytes());  
		    push = new PushbackInputStream(bat); // 创建回退流对象,将拆解的字节数组流传入  
		    int temp = 0;  
		    while ((temp = push.read()) != -1) { // push.read()逐字节读取存放在temp中,如果读取完成返回-1  
		       if (temp == ',') { // 判断读取的是否是逗号  
		          push.unread(temp); //回到temp的位置  
		          temp = push.read(); //接着读取字节  
		          System.out.print("(回退" + (char) temp + ") "); // 输出回退的字符  
		       } else {  
		          System.out.print((char) temp); // 否则输出字符  
		       }  
		    }  
	}
	/*
	 * SequenceInputStream:有些情况下,当我们需要从多个输入流中向程序读入数据。此时,可以使用合并流,
	 * 将多个输入流合并成一个SequenceInputStream流对象。
	 * SequenceInputStream会将与之相连接的流集组合成一个输入流并从第一个输入流开始读取,直到到达文件末尾,接着从第二个输入流读取,依次类推,
	 * 直到到达包含的最后一个输入流的文件末尾为止。 合并流的作用是将多个源合并合一个源。其可接收枚举类所封闭的多个字节流对象。
	 */
	public static void sequenceInputStream(){
	
		     // 创建一个合并流的对象  
		     SequenceInputStream sis = null;  
		     // 创建输出流。  
		     BufferedOutputStream bos = null;  
		     try {  
		        // 构建流集合。  
		        Vector<InputStream> vector = new Vector<InputStream>();  
		        vector.addElement(new FileInputStream("D:\text1.txt"));  
		        vector.addElement(new FileInputStream("D:\text2.txt"));  
		        vector.addElement(new FileInputStream("D:\text3.txt"));  
		        Enumeration<InputStream> e = vector.elements();  
		   
		        sis = new SequenceInputStream(e);  
		   
		        bos = new BufferedOutputStream(new FileOutputStream("D:\text4.txt"));  
		        // 读写数据  
		        byte[] buf = new byte[1024];  
		        int len = 0;  
		        while ((len = sis.read(buf)) != -1) {  
		           bos.write(buf, 0, len);  
		           bos.flush();  
		        }  
		     } catch (FileNotFoundException e1) {  
		        e1.printStackTrace();  
		     } catch (IOException e1) {  
		        e1.printStackTrace();  
		     } finally {  
		        try {  
		           if (sis != null)  
		              sis.close();  
		        } catch (IOException e) {  
		           e.printStackTrace();  
		        }  
		        try {  
		           if (bos != null)  
		              bos.close();  
		        } catch (IOException e) {  
		           e.printStackTrace();  
		        }  
		     }  
		  }  
		/*
		 * PrintStream 
		 * System.out.println();
		 * 
		 */
	}
字符流
/**
 * 字符流测试
 * @author hc
 *
 */
public class Test2 {
	public static void main(String[] args) throws IOException {
		//test1();
	}
	//FileReader ,PrintWriter
	public static void test1() throws IOException{
		char[] buffer=new char[512];   //一次取出的字节数大小,缓冲区大小  
	    int numberRead=0;  
	    FileReader reader=null;        //读取字符文件的流  
	    PrintWriter writer=null;    //写字符到控制台的流  
	     
	    try {  
	       reader=new FileReader("D:/David/Java/java 高级进阶/files/copy1.txt");  
	       writer=new PrintWriter(System.out);  //PrintWriter可以输出字符到文件,也可以输出到控制台  
	       while ((numberRead=reader.read(buffer))!=-1) {  
	          writer.write(buffer, 0, numberRead);  
	       }  
	    } catch (IOException e) {  
	       // TODO自动生成的 catch 块  
	       e.printStackTrace();  
	    }finally{  
	       try {  
	          reader.close();  
	       } catch (IOException e) {  
	          // TODO自动生成的 catch 块  
	          e.printStackTrace();  
	       }  
	       writer.close();       //这个不用抛异常  
	    }  
	}
	/*
	 * bufferedReader/bufferedWriter
	 */
	public static void bufferWri(String...fileName){
		
		  String str;  
		     //构建对该文件您的输入流  
		     BufferedWriter writer=new BufferedWriter(new FileWriter("D:/David/Java/java 高级进阶/files/copy2.txt"));  
		     for(String name: fileName){  
		        BufferedReader reader=new BufferedReader(new FileReader(name));  
		         
		        while ((str=reader.readLine())!=null) {  
		           writer.write(str);  
		           writer.newLine();  
		        }  
		     }  
	}
	
}
原文地址:https://www.cnblogs.com/woolhc/p/4970105.html