且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中数据输入输出流——DataInputStream和DataOutputStream

更新时间:2022-09-12 22:28:05

一、基本概念

DataOutputStream
数据输出流允许应用程序以适当方式将基本 Java 数据类型写入输出流中。然后应用程序可以使用数据输入流将数据读入。

DataOutputStream
数据输入流允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型。应用程序可以使用数据输出流写入稍后由数据输入流读取的数据。对于多线程访问不一定是安全的。 线程安全是可选的,它由此类方法的使用者负责。

 

二、例子
 


  1. /**  
  2.  * 必须先使用DataOutputStream写入数据,然后使用DataInputStream读取数据方可。  
  3.  *   
  4.  * @author 徐越  
  5.  *   
  6.  */ 
  7. public class TestClass  
  8. {  
  9.     public static void main(String[] args) throws Exception  
  10.     {  
  11.         TestClass t = new TestClass();  
  12.         t.write();  
  13.         t.read();  
  14.     }  
  15.  
  16.     public void write() throws Exception  
  17.     {  
  18.         String path = this.getClass().getClassLoader().getResource("test.txt").toURI().getPath();  
  19.         OutputStream os = new FileOutputStream(path);  
  20.         DataOutputStream dos = new DataOutputStream(os);  
  21.         dos.writeDouble(Math.random());  
  22.         dos.writeBoolean(true);  
  23.         dos.writeInt(1000);  
  24.         dos.writeInt(2000);  
  25.         dos.flush();  
  26.         os.close();  
  27.         dos.close();  
  28.     }  
  29.  
  30.     public void read() throws Exception  
  31.     {  
  32.         InputStream instream = this.getClass().getClassLoader().getResourceAsStream("test.txt");  
  33.         DataInputStream dis = new DataInputStream(instream);  
  34.         double d = dis.readDouble();  
  35.         boolean b = dis.readBoolean();  
  36.         // 先写的先被读出来  
  37.         int i1 = dis.readInt();  
  38.         int i2 = dis.readInt();  
  39.         instream.close();  
  40.         dis.close();  
  41.         System.out.println(d);  
  42.         System.out.println(b);  
  43.         System.out.println(i1);  
  44.         System.out.println(i2);  
  45.     }  

输出结果

0.4683893857027681
true
1000
2000

本文转自IT徐胖子的专栏博客51CTO博客,原文链接http://blog.51cto.com/woshixy/1099035如需转载请自行联系原作者


woshixuye111