为了方便地操作Java语言的基本数据类型的数据,可以使用数据流。
数据流有两个类:(用于读取和写出基本数据类型的数据)
DataInputStream 和 DataOutputStream
分别“套接”在 InputStream 和 OutputStream 节点流上
DataInputStream中的方法
boolean readBoolean() byte readByte()
char readChar() float readFloat()
double readDouble() short readShort()
long readLong() int readInt()
String readUTF() void readFully(byte[] b)
DataOutputStream中的方法
将上述的方法的read改为相应的write即可。
package com.xatu.IO;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.annotation.Target;
import org.junit.Test;
public class DataStreamTest {
@Test
public void writeFile() {
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
fos = new FileOutputStream("二进制文件");
dos = new DataOutputStream(fos);
int i =100;
boolean b1= false;
boolean b2 = true;
float f = 3.14f;
long l = 12;
String str = "fdgsr烦不烦";
dos.writeInt(i);
dos.writeBoolean(b1);
dos.writeBoolean(b2);
dos.writeFloat(f);
dos.writeLong(l);
dos.writeUTF(str);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (dos != null)
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void readFile() {
FileInputStream fis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream("二进制文件");
dis = new DataInputStream(fis);
int num = dis.readInt();
boolean b1 = dis.readBoolean();
boolean b2 = dis.readBoolean();
float num2 = dis.readFloat();
long l = dis.readLong();
String str = dis.readUTF();
System.out.println(num);
System.out.println(b1);
System.out.println(b2);
System.out.println(num2);
System.out.println(l);
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(dis != null)
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}