欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

再次出发:字节字符转换流

程序员文章站 2022-03-31 16:59:51
...

字节字符转换流

  • InputStreamReader将输入的字节流转换成字符流输入形式
  • OutputStreamWriter将输出的字符流转换成字节流输出形式
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;

/**
 * 转换流
 *  InputStreamReader将输入的字节流转换成字符流输入形式 
 * OutputStreamWriter将输出的字符流转换成字节流输出形式
 * 
 * @author wuzl
 *
 */
public class test06 {
	public static void read(InputStream in) {
		Reader reader = new InputStreamReader(in);
		char[] ch = new char[1];
		StringBuilder str=new StringBuilder();
		int len = -1;
		try {
			while ((len = reader.read(ch)) != -1) {
				str.append(new String(ch));
			}
			System.out.println(str);
			reader.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	public static void write(OutputStream out) {
		Writer write=new OutputStreamWriter(out);
		try {
			write.write("还有谁?");
			write.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		InputStream input;
		try {
			input = new FileInputStream("C:\\Users\\25316\\Desktop\\wu\\test03.txt");
			read(input);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			OutputStream output=new FileOutputStream("C:\\Users\\25316\\Desktop\\wu\\test03.txt",true);
			//在文件test03.txt会增加“还有谁?”
			write(output);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}

}

相关标签: 字符字节转换流