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

    1. 使用字节流FileInputStream / FileOutputStream 复制文本文件案例:

    分析:

    (1)数据源:从哪里来

    a.txt   --   读取数据  --  FileInputStream

    (2)目的地:到哪里去

    b.txt   --   写数据    --   FileOutputStream

    2. 代码示例:

     1 package cn.itcast_03;
     2 
     3 import java.io.FileInputStream;
     4 import java.io.FileOutputStream;
     5 import java.io.IOException;
     6 
     7 /*
     8  * 复制文本文件。
     9  * 
    10  * 数据源:从哪里来
    11  * a.txt    --    读取数据    --    FileInputStream    
    12  * 
    13  * 目的地:到哪里去
    14  * b.txt    --    写数据        --    FileOutputStream
    15  * 
    16  * java.io.FileNotFoundException: a.txt (系统找不到指定的文件。)
    17  * 
    18  * 这一次复制中文没有出现任何问题,为什么呢?
    19  * 上一次我们出现问题的原因在于我们每次获取到一个字节数据,就把该字节数据转换为了字符数据,然后输出到控制台。
    20  * 而这一次呢?确实通过IO流读取数据,写到文本文件,你读取一个字节,我就写入一个字节,你没有做任何的转换。
    21  * 它会自己做转换。
    22  */
    23 public class CopyFileDemo {
    24     public static void main(String[] args) throws IOException {
    25         // 封装数据源
    26         FileInputStream fis = new FileInputStream("a.txt");
    27         // 封装目的地
    28         FileOutputStream fos = new FileOutputStream("b.txt");
    29 
    30         int by = 0;
    31         while ((by = fis.read()) != -1) {
    32             fos.write(by);
    33         }
    34 
    35         // 释放资源(先关谁都行)
    36         fos.close();
    37         fis.close();
    38     }
    39 }

    运行效果,如下:

  • 相关阅读:
    Mysql 重置密码
    windows下如何安装和启动MySQL
    连接到 PostgreSQL 数据源(SQL Server 导入和导出向导)
    通过apt-get安装JDK8
    Windows 更快捷方便的安装软件,命令提示符上安装 Chocolatey
    Windows 的命令行安装Scoop程序管理工具
    CentOS 7更改yum源与更新系统
    Mysql 获取表设计查询语句
    坐标3度带与6度带的知识(转载)
    jQuery学习---第三天
  • 原文地址:https://www.cnblogs.com/hebao0514/p/4860666.html
Copyright © 2011-2022 走看看