Java核心技术——二进制文件的读写

今天学习了使用Java读写二进制文件,略有所得,不错!

先来补课:

 

代码如下:

写二进制文件:

import java.io.*;
public class BinFileWrite{
  public static void main(String[] args) throws Exception{
	writeFile();
    System.out.println("done.");
  }
  
  public static void writeFile() {
	  FileOutputStream fos = null;
	  DataOutputStream dos = null;
	  BufferedOutputStream bos = null;
		try {
			fos = new FileOutputStream("c:/temp/tbd.dat"); // 节点类
			bos = new BufferedOutputStream(fos); // 装饰类
			dos = new DataOutputStream(bos); // 装饰类		
			
			dos.writeInt(2020);
			dos.writeUTF("is a new start!");
			dos.writeInt(2050);
			dos.writeUTF("is full of hope!");
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				dos.close(); // 关闭最后一个类,会将所有的底层流都关闭
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
}

文件写入(创建)成功后,使用Notepad++打开后,发现数字部分不可读,这正说明了二进制文件并不是记事本等文本处理软件的处理对象。

 

解铃还需系铃人,且看读二进制文件的代码:

import java.io.*;
public class BinFileRead{
  public static void main(String[] args) throws Exception{
	  readFile();
  }
  public static void readFile() {
		//try-resource 语句,自动关闭资源
		try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream("c:/temp/tbd.dat")))) {
			String b, d;
		    int a, c;
		    a=dis.readInt();
		    b=dis.readUTF();
		    c=dis.readInt();
		    d=dis.readUTF();
		    System.out.println("a: "+a);
		    System.out.println("b: "+b);
		    System.out.println("c: "+c);
		    System.out.println("d: "+d);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
}

运行结果:

a: 2020

b: is a new start!

c: 2050

d: is full of hope!

 

 

不难发现,为了正确读入二进制文件中的内容, 需要知道写入时的顺序及内容。如,写入的内容为:

            dos.writeInt(2020);
            dos.writeUTF("is a new start!");
            dos.writeInt(2050);
            dos.writeUTF("is full of hope!");

则,读取时的语句与上述过程是依次对应的:

            a=dis.readInt();
            b=dis.readUTF();
            c=dis.readInt();
            d=dis.readUTF();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值