处理流

处理流

输入流: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();
    }
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值