Java_IO 文件输入流(FileInputStream)与文件输出流(FileOutputStream)

本文探讨了Java.IO中的FileInputStream和FileOutputStream,详细解释如何使用这两个类进行文件的读取和写入操作。通过示例1展示了如何从文件系统中将文件读取到程序内存,而在示例2中,演示了如何将内存中的数据写入文件系统的其他位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FileInputStream和FileOutputStream:用于磁盘、光盘或其他存储设备中文件的字节流的读写

  • 1 从文件系统中读取文件到程序(内存中)

    example1:(FileInputStream从文件系统中读取字节)

 package com.yxstudy;

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

public class ByteReader{

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        char seq = File.separatorChar;//这种方式适用于任何操作系统
       try {
        FileInputStream  fis = new FileInputStream("D:"+seq+"temp"+seq+"1-130G409554O34.jpg");//
        boolean eof = false;//是否到达文件末尾
        byte[]  buffer = new byte[512];//每次读取的字节
        int count = 0;
        while (!eof) {
            int input = fis.read(buffer, 0, buffer.length);
            System.out.print(input+ " ");
            if (input==-1) 
                eof = true;//如果到达文件末尾,则将此标志赋值为true,退出while循环。
            else
                count++;    //记录读取的次数
        }
        fis.close();//释放资源
        System.out.println("\nBytes array readCount: " + count);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("Error --" + e.toString());
    }
    }

}

example2: 先把文件读到内存中在输出到文件系统其他文件夹(文件输出流中)

package com.yxstudy;

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

public class ByteWriter {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        char seq = File.separatorChar;
        try {
            FileInputStream  fis = new FileInputStream("D:"+seq+"temp"+seq+"1-130G409554O34.jpg");
            FileOutputStream  fos = new FileOutputStream("D:"+seq+"temp_dst"+seq+"copy.jpg");//temp_dst目录必须存在
            byte[]  buff = new byte[1024];
            int length = 0;
            while((length = fis.read(buff))!=-1){
                fos.write(buff, 0, length);
            }
            fis.close();
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Error --" + e.toString());
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值