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 }
  • 相关阅读:
    c++基础_矩阵乘法
    c++基础_字符串对比
    c++基础_时间转换
    c++基础_特殊回文数
    c++基础_回文数
    c++基础_特殊的数字
    c++基础_杨辉三角形
    c++基础_字母图形
    c++基础_01字串
    java 常用集合类型--以及其特性
  • 原文地址:https://www.cnblogs.com/ganhang-acm/p/5154304.html
Copyright © 2011-2022 走看看