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

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

一、基本概念

DataOutputStream

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

DataInputStream

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

 

二、例子

/** * 必须先使用DataOutputStream写入数据,然后使用DataInputStream读取数据方可。 *  * @author xy *  */public class TestClasspublic static void main(String[] args) throws Exception {  TestClass t = new TestClass();  t.write();  t.read(); } public void write() throws Exception {  String path = this.getClass().getClassLoader().getResource("test.txt").toURI().getPath();  OutputStream os = new FileOutputStream(path);  DataOutputStream dos = new DataOutputStream(os);  dos.writeDouble(Math.random());  dos.writeBoolean(true);  dos.writeInt(1000);  dos.writeInt(2000);  dos.flush();  os.close();  dos.close(); } public void read() throws Exception {  InputStream instream = this.getClass().getClassLoader().getResourceAsStream("test.txt");  DataInputStream dis = new DataInputStream(instream);  double d = dis.readDouble();  boolean b = dis.readBoolean();  // 先写的先被读出来  int i1 = dis.readInt();  int i2 = dis.readInt();  instream.close();  dis.close();  System.out.println(d);  System.out.println(b);  System.out.println(i1);  System.out.println(i2); }}

输出结果

0.4683893857027681
true
1000
2000

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/hdsghtj/article/details/83926228