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来作为输入输出流,这样可以显得程序易读。事实上更多情况下是使用文件流来进行输出输入。
相关文章推荐
- Java JNI 编程进阶 实例+c++数据类型与jni数据类型转换
- 大数据生态系统基础:Apache Spark(三):Java 版本编程实例(WordCount)
- Java多线程编程之使用Exchanger数据交换实例
- Java编程通过匹配合并数据实例解析(数据预处理)
- Java网络编程实例---------------------------------TCP和UDP发送数据统计
- 一个简单的SWT程序实例及详解-Java基础-Java-编程开发
- java中删除数据库中重复数据的几个方法-Java基础-Java-编程开发
- 新手入门:Java XML编程实例解析
- java操作xml编程实例(sax)
- java操作xml编程实例(sax)
- JAVA程序通过后台登陆网站,获取Session,然后再POST Http Request添加数据到数据库的实例
- AJAX for Java简单表数据查询实例
- Java socket 入门编程实例-Java基础-Java-编程开发
- 初学者入门 JAVA 的 XML 编程实例解析-Java基础-Java-编程开发
- java基础进阶(文件列表,线程,线程组)编程实例(4篇)
- 初学者入门 JAVA 的 XML 编程实例解析
- 使用Java API压缩和解压缩数据-Java基础-Java-编程开发
- 新手入门:Java XML编程实例解析
- AJAX for Java简单表数据查询实例
- Java 编程基础,应用与实例