zoukankan      html  css  js  c++  java
  • Java基础知识强化之IO流笔记36:InputStreamReader/OutputStreamWriter 复制文本文件案例

    1. 需求:把当前项目目录下的a.txt内容复制到当前项目目录下的b.txt中.
     数据源:
       a.txt -- 读取数据 -- 字符转换流 -- InputStreamReader
     目的地:
       b.txt -- 写出数据 -- 字符转换流 -- OutputStreamWriter

     InputStreamReader/OutputStreamWriter不仅是转换流(将字节流转换为字符流),也是字符流Reader/Writer的具体实现子类

    2.代码示例:

     1 package cn.itcast_04;
     2 
     3 import java.io.FileInputStream;
     4 import java.io.FileOutputStream;
     5 import java.io.IOException;
     6 import java.io.InputStreamReader;
     7 import java.io.OutputStreamWriter;
     8 
     9 /*
    10  * 需求:把当前项目目录下的a.txt内容复制到当前项目目录下的b.txt中
    11  * 
    12  * 数据源:
    13  *         a.txt -- 读取数据 -- 字符转换流 -- InputStreamReader
    14  * 目的地:
    15  *         b.txt -- 写出数据 -- 字符转换流 -- OutputStreamWriter
    16  */
    17 public class CopyFileDemo {
    18     public static void main(String[] args) throws IOException {
    19         // 封装数据源
    20         InputStreamReader isr = new InputStreamReader(new FileInputStream(
    21                 "a.txt"));
    22         // 封装目的地
    23         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
    24                 "b.txt"));
    25 
    26         // 读写数据
    27         // 方式1
    28         // int ch = 0;
    29         // while ((ch = isr.read()) != -1) {
    30         // osw.write(ch);
    31         // }
    32 
    33         // 方式2
    34         char[] chs = new char[1024];
    35         int len = 0;
    36         while ((len = isr.read(chs)) != -1) {
    37             osw.write(chs, 0, len);
    38             // osw.flush();
    39         }
    40 
    41         // 释放资源
    42         osw.close();
    43         isr.close();
    44     }
    45 }
  • 相关阅读:
    0_Simple__simplePrintf
    0_Simple__simplePitchLinearTexture
    0_Simple__simpleP2P
    0_Simple__simpleOccupancy
    0_Simple__MultiGPU
    0_Simple__simpleMultiCopy
    0_Simple__simpleMPI
    0_Simple__simpleLayeredTexture
    0_Simple__simpleCubemapTexture
    0_Simple__simpleCooperativeGroups
  • 原文地址:https://www.cnblogs.com/hebao0514/p/4868488.html
Copyright © 2011-2022 走看看