码迷,mamicode.com
首页 > 编程语言 > 详细

Java IO(四)- 转换流

时间:2016-06-13 11:07:13      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:

转换流

InputStreamReader和OutputStreamWriter用于字节数据到字符数据之间的转换。

InputStreamReader需要和InputStream套接(把InputStream转换成InputStreamReader)

OutputStreamWriter需要和OutputStream套接(把OutputStreamWriter转换成OutputStream)

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

InputStream is = new InputStreamReader(System.in, "IOS8859_1");

例子一、

    public static void main(String[] args) {
        try {
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\bak\\char.txt"));
            osw.write("miscalkjsdlasjdlajslkdalksd");
            System.out.println(osw.getEncoding());
            osw.close();
            
            osw = new OutputStreamWriter(new FileOutputStream("d:\\bak\\char.txt", true), "ISO8859_1");//true,追加
            osw.write("sadasdasdasdasd");
            System.out.println(osw.getEncoding());
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

结果:

UTF8//系统默认的编码
ISO8859_1

例子二、

    public static void main(String[] args) {
        try {
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            String s = null;
            s = br.readLine();
            while(s != null) {
                if("exit".equalsIgnoreCase(s))
                    break;
                System.out.println(s.toUpperCase());
                s = br.readLine();
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

结果:

add111
ADD111
exit

 

Java IO(四)- 转换流

标签:

原文地址:http://www.cnblogs.com/lemon-now/p/5579544.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!