读写二进制数据

一.DataInput 和DataOutput接口

  • DataOutput接口定义了下面用于以二进制格式写数组,字符,boolean值和字符串的方法:
 public void writeBoolean(boolean v) throws IOException {}
 public void writeByte(int v) throws IOException {}
 public void writeShort(int v) throws IOException {}
 public void writeChar(int v) throws IOException {}
 public void writeInt(int v) throws IOException {}
 public void writeLong(long v) throws IOException {}
 public void writeFloat(float v) throws IOException {}
 public void writeDouble(double v) throws IOException {}
 public void writeBytes(String s) throws IOException {}
 public void writeChars(String s) throws IOException {}
 public void writeUTF(String s) throws IOException {}
  • 例如,writeInt总是将一个整数写出为4字节的二进制数量值,而不管它有多少位,writeDouble总是将一个double值写出为8字节的二进制数量值。
  • writeUTF方法使用修订版的8位Unicode转换格式写出字符串。这种方式与直接使用标准的UTF-8编码方式不同。其中,Unicode码元序列首先用UTF-16表示,其结果之后使用UTF-8规则进行编码。修订后的编码方式大于0xFFFF的字符的处理有所不同,这是为了向后兼容在Unicode还没有超过16位时构建的虚拟机。
  • DataInputStream类实现了DataInput接口,为了从文件中读入二进制数据,可以将DataInputStream与某个字节源相结合,例如FileInputStream
try(DataInputStream din = new DataInputStream(
             new BufferedInputStream(
                 new FileInputStream("C:\\Users\\whz\\Desktop\\百度盘会员.txt")));
            DataOutputStream dos = new DataOutputStream(new FileOutputStream("text.txt"));
            ) 
            {
            byte[] bytes = new byte[1000];
            while (din.read() != -1){
                din.read(bytes);
                dos.write(bytes);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值