处理流

本文深入讲解Java中IO流的应用,包括DataInputStream和DataOutputStream的使用方法,如何进行数据类型的读写操作,以及处理字节流和文件流的具体实现。通过实例演示了数据的序列化过程,从文件和字节数组中读取数据类型,如double、long和String,并展示了流的关闭和缓冲区的使用。

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

处理流

输入流:DataInputStream

输出流:DataOutputStream

数据+类型的输入输出

import java.io.*;

/**
 * 数据类型(基本+String)处理流
 * DataInputStream
 * DataOutputStream
 * java.io.EOFException 没有读取到相关的内容
 */
public class Demo08 {
    public static void main(String[] args) throws IOException {
       write("D:/test.txt");
       read("D:test.txt");
       readByte(writeByte());
    }
    /**
     * 从文件读取数据类型
     */
    public static void read(String srcPath) throws IOException {
        //创建源
        File src=new File(srcPath);
        //选择流
        DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream(src)));
        //读取
        double d=dis.readDouble();
        long l=dis.readLong();
        String str=dis.readUTF();
        System.out.println(str);
        dis.close();
    }
    /**
     * 数据+类型输出到文件
     * @param destPath
     * @throws IOException
     */
    public static void write(String destPath) throws IOException {
        double point=2.5;
        long num=100L;
        String str="数据类型";
        //创建源
        File dest=new File(destPath);
        //选择流
        DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
        //写出的顺序为读取准备,保持一致,不按顺序,数据会出错
        dos.writeDouble(point);
        dos.writeLong(num);
        dos.writeUTF(str);
        dos.flush();
        dos.close();

    }
    /**
     * 数据+类型输出到字节数组
     */
    public static byte[] writeByte() throws IOException {
        double point=2.5;
        long num=100L;
        String str="数据类型";
        byte[] dest=null;
        //选择流
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(bos));
        //写出的顺序为读取准备,保持一致,不按顺序,数据会出错
        dos.writeDouble(point);
        dos.writeLong(num);
        dos.writeUTF(str);
        dos.flush();
        dest=bos.toByteArray();
        dos.close();
        return dest;
    }
    /**
     * 从字节数组读取数据+类型
     */
    public static void readByte(byte[] src) throws IOException {
        DataInputStream dis=new DataInputStream(new BufferedInputStream(new ByteArrayInputStream(src)));
        //读取
        double d=dis.readDouble();
        long l=dis.readLong();
        String str=dis.readUTF();
        System.out.println(d+"-->"+l+"-->"+str);
        dis.close();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值