14 IO流(十一)——装换流InputStreamReader与OutputStreamWriter

什么是转换流

首先,这里的转换流指的是InputstreamReader与OutputStreamWriter。

正如它们的名字,它的作用是将字节流转换为字符流。

为什么要转换为字符流呢?因为对于获取到的字节流,如果是纯文本数据,还是建议转换为字符流来处理比较方便且高效。

构造器

特别需要提到的一点:InputStreamReader(InputStream in,String charset) 与 OutputStreamWriter(OutputStream ou,String charset)

它们可以指定一个字符集,使得字节流转换为字符流时按照此字符集进行编码。

如不指定字符集,在Eclipse中与Project的字符集相同。

关键代码解析

BufferedWriter bw = 
		new BufferedWriter(
	       new OutputStreamWriter(
			new FileOutputStream("baidu.txt"),"iso-8859-1"))){

  

这个输出流要怎么理解呢?

首先,我们已经确定了要输出的是纯文本数据,输出为文件,那就可以选择两个流:FileOutputStream与FileWriter。那为什么选择前者不选择后者呢?因为我们需要对输出流的字符集进行设置,有这个功能的就是我们的转换流了。而转换流需要有一个用来转换的字节流,于是FileOutputStream就成了不二之选。

然后写BufferedWriter的原因,是因为OutputStreamWriter已经将FileOutputStream字节流转为了字符流,为了高效的运作,也为了配套使用,就要写BufferedWriter啦。

例子一:System.in与System.out两个字节流转换为字符流

import java.io.*;
public class IOTest03
{
	/**
	*字节流转字符流
	*这里以System.in与System.out两个字节流为例子
	*/
	public static void main(String[] args){
		//创建流
		try(BufferedReader br =	//由于字节流转为字符流,我们应该习惯性的包装一下
			new BufferedReader(
				new InputStreamReader(System.in,"utf-8"));
		BufferedWriter bw = 
			new BufferedWriter(
				new OutputStreamWriter(System.out,"iso-8859-1"))){
			String msg = "";
			while(!msg.equals("exit")){//循环读取与输出,直到读到“exit”
				msg = br.readLine();
				bw.write(msg);
				bw.newLine();
				bw.flush();
				//System.out.println(line);
			}
		}catch(IOException e){
			e.printStackTrace();
			System.err.println("流读取错误");
		}
	}
}

  

例子二:从网络获取一个流

这里使用new URL("www.baidu.com").openStream()的方法创建一个流作为输入流(它是字节流)

将其输出到文件。

import java.io.*;
import java.net.URL;
public class IOTest04
{
	/**
	*字节流转字符流
	*从网络获取一个流作为输入流
	*/
	public static void main(String[] args){
		//创建流
		try(BufferedReader br = 
			new BufferedReader(
				new InputStreamReader(
					new URL("http://www.baidu.com").openStream(),"utf-8"));
			BufferedWriter bw = 
				new BufferedWriter(
					new OutputStreamWriter(
						new FileOutputStream("baidu.txt"),"iso-8859-1"))){//使用8859,中文内容会乱码
			//操作
			String line = "";
			while((line = br.readLine())!=null){
				System.out.print(line);
				bw.write(line);
				bw.flush();
			}
			
			
		}catch(IOException e){
			e.printStackTrace();
			System.out.println("流异常");
		}
	}
}

  

原文地址:https://www.cnblogs.com/Scorpicat/p/11924644.html