java读写二进制文件

写入二进制文件,用ultraEdit打开看data1.dat,内容为

 

 

/* 
 * 演示了写入二进制数据到一个文件中
 * */
import java.io.*;

public class Ex6_7 {

	public static void main(String[] args) {
		String fileName = "c:/data1.dat";
		
		// 将这几个数写到文件中
		int intV1 = 255, intV2 = 0, intV3 = -1, intV4 = 0,intV5 = 15;
		long long1 = 2, long2 = 0,long3 = 15;

		try {
			// 看DataOutputStream怎么连接到一个FileOutputStream
			DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));
			
			// 写基本类型数据
			out.writeInt(intV1);
			out.writeInt(intV2);
			out.writeInt(intV3);
			out.writeInt(intV4);
			out.writeInt(intV5);
			out.writeLong(long1);
			out.writeLong(long2);
			out.writeLong(long3);
			out.close();
		} catch (IOException e) {
		}
	}
}

 读二进制文件,读出一个数(int为32位)后,会抛弃已读的流,再调用read方法会从33位开始。所以编码人员不用做截取。

 

public class Read {
	public static void main(String[] args) {
		String fileName = "c:/data1.dat";
		try {
			DataInputStream dis = new DataInputStream(new FileInputStream(fileName));
			System.out.println(dis.readInt());
			System.out.println(dis.readInt());
			System.out.println(dis.readInt());
			System.out.println(dis.readInt());
			System.out.println(dis.readInt());
			System.out.println(dis.readLong());
			System.out.println(dis.readLong());
			System.out.println(dis.readLong());dis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(java)