Java基础回顾 : 处理流(缓冲流)

首先,来看一下 , 流的分类 :

① . 流的方向 :
        输入流 :数据源到程序(InputStream、Reader读进来)
        输出流 : 程序到目的地(OutputStream、Writer写出去)
② . 处理数据单元 :
        字节流 : 按照字节读取数据(InputStream、OutputStream)
        字符流 : 按照字符读取数据(Reader、Writer)
③ . 功能不同 :
        节点流 : 可以直接从数据源或目的地读写数据
        处理流 : 不直接连接到数据源或目的地 , 是处理流的流 , 通过对其他流的处理提高程序的性能 .
节点流和处理流的关系 :
        节点流处于IO操作的第一线 , 所有操作必须通过他们进行 ;处理流在节点流之上,可以对其他流进行处理(提高效率或操作灵活性)


eg : 使用缓冲流对文件进行操作 :

package example;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
/**
 * 文件的操作,加入缓冲流,提高性能.
 * @author Miao
 *
 */
public class TestDemo {
	public static void main(String[] args) throws Exception {
		
	}
	
	/**
	 * 用字节缓冲输出流,往指定文件输入内容
	 * @throws Exception
	 */
	public static void store() throws Exception {
		String msg = "好好学习,天天向上.";
		File destFile = new File("e:\\msg\\msg.txt");
		if(!destFile.getParentFile().exists()) {
			destFile.getParentFile().mkdirs();
		}
		//加入缓冲流,提高性能.因为BufferedOutputStream类中没有新增方法,可以使用向上转型
		OutputStream is = new BufferedOutputStream(new FileOutputStream(destFile));
		byte data[] = msg.getBytes();
		is.write(data);
		is.flush();
		is.close();
	}
	
	/**
	 * 用字节缓冲输入流,从指定文件中输出内容
	 * @throws Exception
	 */
	public static void load() throws Exception{
		File srcFile = new File("e:\\msg\\msg.txt");
		if(srcFile.exists()) {
			//加入缓冲流,提高性能.因为BufferedInputStream类中没有新增方法,可以使用向上转型
			InputStream is = new BufferedInputStream(new FileInputStream(srcFile));
			byte buf[] = new byte[1024];
			int len = 0;
			while((len=is.read(buf)) != -1) {
				System.out.println(new String(buf,0,len));
			}
			is.close();
		}
	}
	
	/**
	 * 用字符缓冲输出流,往指定文件输入内容
	 * @throws Exception
	 */
	public static void save() throws Exception{
		String msg = "好好学习,天天向上.";
		File destFile = new File("e:\\msg\\msg.txt");
		if(!destFile.getParentFile().exists()) {
			destFile.getParentFile().mkdirs();
		}
		//加入缓冲流,使用新增方法,不能用向上转型
		BufferedWriter writer = new BufferedWriter(new FileWriter(destFile));
		writer.write(msg);
		//新增的方法newLine()
		writer.newLine();
		writer.flush();
		writer.close();
	}
	
	/**
	 * 用字符缓冲输入流,从指定文件中输出内容
	 * @throws Exception
	 */
	public static void get() throws Exception {
		File srcFile = new File("e:\\msg\\msg.txt");
		if(srcFile.exists()) {
			//加入字符缓冲流,使用新增方法,不能用向上转型
			BufferedReader reader = new BufferedReader(new FileReader(srcFile));
			String buf = null;
			//新增方法readLine()
			while((buf=reader.readLine()) != null) {
				System.out.println(new String(buf));
			}
			reader.close();
		}
	}
}


猜你喜欢

转载自blog.csdn.net/sinat_18882775/article/details/51545465
今日推荐