zoukankan      html  css  js  c++  java
  • java学习之字符流与字节流的转换

     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 }
  • 相关阅读:
    bzoj1208 宠物收养所treap/splay/set
    Angular 下的 function
    argunlar 1.0.1 【数据绑定】
    argunlar 1.0.0 【hello,world】
    JavaScript编写风格指南 (三)
    JavaScript编写风格指南 (二)
    JavaScript编写风格指南 (一)
    AngularJS开发指南:表达式
    HTML5 移动开发(移动设备检测及对HTML5的支持)
    HTML5 移动开发(CSS3设计移动页面样式)
  • 原文地址:https://www.cnblogs.com/ganhang-acm/p/5154304.html
Copyright © 2011-2022 走看看