您的位置:首页 > 编程语言 > Java开发

Java流编程实例之六--数据流

2016-09-28 20:35 239 查看

7. 数据流

数据流DataOutputStream和DataInputStream用来将Java的简单数据类型和字符串保存为二进制格式,并从二进制格式读取。使用它们时需要注意以下几点:

第一,DataOutputStream输出的二进制流,必须使用DataInputStream读入,且各个变量的输出输出顺序必须相同;

第二,boolean,byte,short,char,int,long,float,double和String可以使用相应的write和read方法进行输出和输入,例如writeInt和readInt;

第三,输入输出字符串时使用readUTF和writeUTF,避免使用writeChars和wirteBytes等方法。因为writeUTF方法中将字符串长度一并保存,所以在readUTF中可以正确读取。

例子如下:

public static void dataOutputStreamExam() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
boolean b = true;
dos.writeBoolean(b);
showDataByte(baos);

byte by = 0x03;
dos.writeByte(by);
showDataByte(baos);

short sh = 42;
dos.writeShort(sh);
showDataByte(baos);

char c = '一';
dos.writeChar(c);
showDataByte(baos);

int i = 1234567;
dos.writeInt(i);
showDataByte(baos);

long l = 12345678L;
dos.writeLong(l);
showDataByte(baos);

float f = 3.1415926f;
dos.writeFloat(f);
showDataByte(baos);

double dou = 3.1415926535;
dos.writeDouble(dou);
showDataByte(baos);

String s = "This is a good day. 今天是个好天气.";
dos.writeUTF(s);
showDataByte(baos);

int i2 =233;
dos.writeInt(i2);
showDataByte(baos);

dos.flush();
baos.flush();

//依次读取数据
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(baos.toByteArray()));
b = dis.readBoolean();
System.out.println(b);
by = dis.readByte();
System.out.println(by);
sh =dis.readShort();
System.out.println(sh);
c=dis.readChar();
System.out.println(c);
i=dis.readInt();
System.out.println(i);
l=dis.readLong();
System.out.println(l);
f=dis.readFloat();
System.out.println(f);
dou=dis.readDouble();
System.out.println(dou);
s=dis.readUTF();
System.out.println(s);
i2=dis.readInt();
System.out.println(i2);
dis.close();

dos.close();
} catch (IOException e) {
e.printStackTrace();
}

}

public static void showDataByte(ByteArrayOutputStream baos) {
byte[] buf = baos.toByteArray();
for (int j = 0; j < buf.length; j++) {
System.out.print( byteToHexString(buf[j])+",");
}
System.out.println("------------------------------");
}

public static String byteToHexString(byte b) {
String s = Integer.toHexString(b);
int len = s.length();
if (len >= 2) {
s = s.substring(len - 2);
}else{
s = "0"+s;
}
return s;
}


例子中使用了ByteArrayOutputStream和ByteArrayInputStream来作为输入输出流,这样可以显得程序易读。事实上更多情况下是使用文件流来进行输出输入。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: