IO流 文件字节流FileInputStream、FileOutStream

8 篇文章 0 订阅

IO流

引入

当我们需要对文件内容与程序交互时,就需要一个“通道”来传递数据,即IO流
在这里插入图片描述

分类

在这里插入图片描述

处理流和节点流

处理流:多个IO流结合间接接触目标文件
节点流:单个IO流直接接触目标文件

文件—>程序 FileInputStream

过程

  1. 确定目标文件
  2. 建立文件到程序的IO流
  3. 开始具体操作“动作”
  4. 关闭IO流
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamTest {
    public static void main(String[] args) throws IOException {
        File file = new File("D:\\test\\a\\test01.txt");  //操纵对象
        FileInputStream fileInputStream = new FileInputStream(file);  //创建对象

        System.out.println(fileInputStream.available());  //获取文件字节长度
        
        int read = fileInputStream.read();   //按字节长度读取文件
        while (read!=-1){
            System.out.println(((char)read));
            read = fileInputStream.read();
        }
        fileInputStream.close();//关闭IO流
    }
}

在这里插入图片描述

程序—>文件 OutputStream

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileInputStreamTest {
    public static void main(String[] args) throws IOException {
        File file = new File("D:\\test\\a\\test01.txt");  //操纵对象
        FileOutputStream fileOutputStream = new FileOutputStream(file,true);  //程序---》文件,可拓展参数true
        String s ="123!";
        byte[] bytes = s.getBytes();             //将字符串转为字节数组
        fileOutputStream.write(bytes);          //写入字节
        fileOutputStream.close();              //关闭IO流

        FileInputStream fileInputStream = new FileInputStream(file); //文件---》程序
        int read = fileInputStream.read();             //依次读出文件字节

        while (read!=-1){
            System.out.print((char) read);
            read = fileInputStream.read();
        }
        fileInputStream.close();     //关闭IO流
    }
}

在这里插入图片描述

  • 每执行一次程序就会写入"123!"字符串

综合应用 文件复制

import java.io.*;

public class Test02 {
    public static void main(String[] args) throws IOException {
        File file1 = new File("D:\\test\\a\\test01.txt");  //确定读目标
        File file2 = new File("D:\\test\\a\\test02.txt");  //确定写目标

        FileInputStream fileInputStream = new FileInputStream(file1);   //建立 文件———》程序 IO流
        FileOutputStream fileOutputStream = new FileOutputStream(file2); ///建立 程序--》文件 IO流

        int read = fileInputStream.read();  //读一个字节
        while (read!=-1){
            fileOutputStream.write(read);   //写一个字节
            read = fileInputStream.read();   //继续读下一个字节
        }
         
        fileOutputStream.close();   //关闭IO流
        fileInputStream.close();
    }
}

在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值