字节流转换字符流

InputStreamReader和OutputStreamWriter是为实现这种转换而设计的。

InputStreamReader构造方法如下:

InputStreamReader(InputStream in):将字节流in转换为字符流对象,字符使用默认字符集。

InputStreamReader(InputStream in ,String charsetName):将字节流in转换为字符流对象,charsetName指定字符流的字符集,字符集主要有:US-ASCII、ISO-8859-1、UTF-8和UTF-16。如果指定的字符集不支持会抛出UnsupprtedEncodingException异常。

OutputStreamWriter(Out[utStream out):将字节流out转换为字符流对象,字符流使用默认字符集。

OutputStreamWriter(Out[utStream out,String charsetName):将字节流out转换为字符流对象,charsetName指定字符流的字符集,如果指定的字符集不支持会抛出UnsupprtedEncodingException异常。

代码示例

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class FileIoWriterIo {
	public static void main(String[] args) {
		
		//使用自动资源管理输入流和文件输出流
		try (FileInputStream in = new FileInputStream("./TestDir/index.txt");//文件输入流
				InputStreamReader isr = new InputStreamReader(in);
				BufferedReader bin = new BufferedReader(isr);
				FileOutputStream out = new FileOutputStream("./TestDir/indexxxx.txt",false);//文件输出流,true为覆盖,false为追加
				OutputStreamWriter osw = new OutputStreamWriter(out);
				
				//添加字符缓冲流
				BufferedWriter bout = new BufferedWriter(osw);
				){
			//第一次读取
			String line = bin.readLine();
			//判断循环读取数据
			while (line != null) {
				//数据写入到输出流中
				bout.write(line);
				//添加一个回车符,防止数据格式变化,失真
				bout.newLine();
				//再次读取
				line = bin.readLine();
			}
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章