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

java学习之字符流与字节流的转换

时间:2016-01-24 00:37:17      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

 1 package com.io;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileNotFoundException;
 6 import java.io.IOException;
 7 import java.io.InputStream;
 8 import java.io.InputStreamReader;
 9 /**
10  * 字节流转为字符流读入
11  * @author ganhang
12  *
13  */
14 public class InputStreamReaderDemo {
15     public static void main(String[] args) {
16         File file =new File("1.txt");
17         InputStream in;
18         try {
19             in = new FileInputStream(file);
20             InputStreamReader isr=new InputStreamReader(in);
21             int len=-1;
22             StringBuffer sb=new StringBuffer();
23             char []b=new char[10];
24             while((len=isr.read(b))!=-1){
25                 sb.append(b,0,len);
26             }
27             isr.close();
28             in.close();
29             System.out.println(sb);
30         } catch (FileNotFoundException e) {
31             e.printStackTrace();
32         } catch (IOException e) {
33             e.printStackTrace();
34         }
35     }
36 }
 1 package com.io;
 2 import java.io.File;
 3 import java.io.FileNotFoundException;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.OutputStream;
 7 import java.io.OutputStreamWriter;
 8 /**
 9  * 字符流转为字节写入
10  * @author ganhang
11  *
12  */
13 public class OutputStreamWriterDemo {
14     public static void main(String[] args) {
15         File file=new File ("1.txt");
16         OutputStream out;
17         try {
18             out = new FileOutputStream(file,true);
19             OutputStreamWriter osw=new OutputStreamWriter(out);
20             String info="哈哈哈哈哈哈";
21             osw.write(info);
22             osw.close();
23             out.close();
24             System.out.println("写入成功!");
25         } catch (FileNotFoundException e) {
26             e.printStackTrace();
27         } catch (IOException e) {
28             e.printStackTrace();
29         }
30     }
31 }

 

java学习之字符流与字节流的转换

标签:

原文地址:http://www.cnblogs.com/ganhang-acm/p/5154304.html

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