DataInputStream
类以与机器无关的方式从基础输入流中读取原始Java数据类型。 而DataOutputStream
类以可移植的方式将原始Java数据类型写入输出流。
下面是一个演示DataInputStream
和DataOutputStream
使用的示例。
文件:DataInputOutputStreamExample.java –
package com.yiibai.tutorial.io; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * @author yiibai * DataInputOutputStreamExample.java * Nov 5, 2016 */ public class DataInputOutputStreamExample { public static void main(String[] args) { File file = new File("file.txt"); /*Write primitive data type to file*/ FileOutputStream fileOutputStream = null; DataOutputStream dataOutputStream = null; try { fileOutputStream=new FileOutputStream(file); dataOutputStream=new DataOutputStream(fileOutputStream); dataOutputStream.writeInt(50); dataOutputStream.writeDouble(400.25); dataOutputStream.writeChar('A'); dataOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); }finally { try { if(fileOutputStream!=null){ fileOutputStream.close(); } if(dataOutputStream!=null){ dataOutputStream.close(); } } catch (Exception e) { e.printStackTrace(); } } /*Read primitive data type from file*/ FileInputStream fileInputStream = null; DataInputStream dataInputStream = null; try { fileInputStream = new FileInputStream(file); dataInputStream = new DataInputStream(fileInputStream); System.out.println(dataInputStream.readInt()); System.out.println(dataInputStream.readDouble()); System.out.println(dataInputStream.readChar()); } catch (IOException e) { e.printStackTrace(); }finally { try { if(fileInputStream!=null){ fileInputStream.close(); } if(dataInputStream!=null){ dataInputStream.close(); } } catch (Exception e) { e.printStackTrace(); } } } }
执行上面示例代码,得到以下结果:
50 400.25 A
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264111.html