8.Java基础:常见IO流----->字符流中的转化流:OutputStreamWriter、InputStreamReader

来源:互联网 发布:淘宝冻结账户开通 编辑:程序博客网 时间:2024/05/22 10:44

1.这两个是转换流,他们的作用

1.在字节与字符之间做转换.

2.可以指定编码进行读写操作。


2.InputStreamReader:字节流通向字符流的桥梁

构造

newInputStreamReader(InputStream is);

public class InputStreamReader<span style="font-family: Arial, Helvetica, sans-serif;">Demo</span><span style="font-family: Arial, Helvetica, sans-serif;"> {</span><span style="white-space:pre"></span>public static void main(String[] args) throws IOException {//第一种方案InputStream is = System.in; //获取一个从键盘读取信息的输入流byte[] by= new byte[2];int length = is.read(by);System.out.println(new String(by, 0, length));////第二种方案,手动完成//在System.in外层包装一个流,这个流是字符流,可以直接使用字符流,读取字符InputStreamReader isr = new InputStreamReader(System.in);char[] ch = new char[10];int length = isr.read(ch); //一次读取一个字符System.out.println(new String(ch, 0, length));//System.out.println(String.valueOf(ch, 0, length)); //和上句话效果一样}}


3.OutputStreamWriter:是字符流通向字节流的桥樑

构造

newOutputStreamWriter(OutputStream os)         

//向控制台写入一个汉字public class BufferedReader<span style="font-family: Arial, Helvetica, sans-serif;">Demo </span><span style="font-family: Arial, Helvetica, sans-serif;">{</span><span style="white-space:pre"></span>public static void main(String[] args) throws IOException {<span style="white-space:pre"></span>OutputStreamWriter osw = new OutputStreamWriter(System.out);<span style="white-space:pre"></span>osw.write("我是一个好人");<span style="white-space:pre"></span>osw.flush();<span style="white-space:pre"></span>osw.close();<span style="white-space:pre"></span>}}

4.解决编码乱码

1.原因:new InputStreamReader(InputStream is) 使用默认字符集,与系统默认编码不一样,出现乱码

解决方案:

InputStreamReader(InputStream in, String charsetName) 

创建使用指定字符集的 InputStreamReader。

public class InputStreamReader<span style="font-family: Arial, Helvetica, sans-serif;">Demo</span><span style="font-family: Arial, Helvetica, sans-serif;"> {</span>//读取e盘下a.txt文件public static void main(String[] args) throws FileNotFoundException, IOException {FileInputStream fis = new FileInputStream("e:/a.txt");InputStreamReader isr = new InputStreamReader(fis); //使用UF-8字符集读取//读取文件内容while (true) {int code = isr.read(); //一次读取一个if (code == -1) {break;}System.out.println((char)code);}}}

2.使用OutputStreamWriter时,如果也有编码问题  

解决方案: new OutputStreamWriter(OutputStream os,String charsetname);

public class InputStreamWriter<span style="font-family: Arial, Helvetica, sans-serif;">Demo </span><span style="font-family: Arial, Helvetica, sans-serif;"> {</span>public static void main(String[] args) throws IOException {FileOutputStream fos = new FileOutputStream("e:/a.txt",true);OutputStreamWriter osw = new OutputStreamWriter(fos);osw.write("中国");osw.flush();osw.close();}}


0 0
原创粉丝点击