Java I/O系统之转换流

来源:互联网 发布:淘宝开店审核通过后怎么办 编辑:程序博客网 时间:2024/05/14 05:30

1.转换流介绍

1)        InputStreamReader和OutputStreamWriter用于字节数据到字符数据之间转换

2)        InputStreamReader需要和InputStream“套接”

3)        OutputStreamWriter需要和OutputStream”套接”

4)        转换流在构造时可以指定其编码集合,例如:

InputStream isr = new InputStreamReader(System.in,”ISO8859_1”);

2.转换流例子一

package com.owen.io;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;/** * 使用OutputStreamWriter转换流实现文件写入 *  * @author OwenWilliam 2016-7-19 * @since * @version v1.0.0 * */public class TestTransForm1{@SuppressWarnings("resource")public static void main(String[] args){try{// 写入文件的路径OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("E:/workspace/Java/IO/src/com/owen/io/char.txt"));osw.write("this application will use Stream!");System.out.println(osw.getEncoding());// 写好了记得关闭osw.close();// 后面true指,接着上面写的内容后面继续写,如果去掉,那么就会重新写入(擦去原有的)// 后面ISO8859_1是规定的写入编码osw = new OutputStreamWriter(new FileOutputStream("E:/workspace/Java/IO/src/com/owen/io/char.txt", true),"ISO8859_1");osw.write("it will add in the end text!");System.out.println(osw.getEncoding());osw.close();} catch (IOException e){e.printStackTrace();}}}

3.转换流例子二

package com.owen.io;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** * 使用InputStreamReader实现读取,同时用BufferedReader实现一行一行读取 这里是用到同步的线程,即阻塞。 *  * @author OwenWilliam 2016-7-19 * @since * @version v1.0.0 * */public class TestTransForm2{public static void main(String[] args){// System.in其实是就相当于流“管道”的字节流,然后外面包裹InputStreamReader,实现字节读取InputStreamReader isr = new InputStreamReader(System.in);// 使用BufferedReader,可以实现一行一行的读取BufferedReader br = new BufferedReader(isr);String s = null;try{// 读取一行s = br.readLine();while (s != null){// 退出if (s.equalsIgnoreCase("exit"))break;System.out.println(s.toUpperCase());s = br.readLine();}br.close();} catch (IOException e){// TODO Auto-generated catch blocke.printStackTrace();}}}




0 0