【BigData】Java基础_DataOutputStream与DataInputStream
作者:互联网
简介
DataOutputStream是一个包装流,他可以将各种数据类型的数据再内部转称bytes字节,然后利用FileOutputStream写入文件中,DataInputStream读取文件内容的原理与之类似。
以下是一个使用DataOutputStream将对象写入文件,并且从文件中读取内容的操作
代码部分
package cn.test.logan.day10; public class User { String id; String name; float sal; String addr; public User(){ } public User(String id, String name, float sal, String addr) { super(); this.id = id; this.name = name; this.sal = sal; this.addr = addr; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getSal() { return sal; } public void setSal(float age) { this.sal = sal; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } @Override public String toString() { return "[id=" + id + ", name=" + name + ", sal=" + sal + ", addr=" + addr + "]"; } }User.java
package cn.test.logan.day10; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStreamWriter; public class DataStreamDemo { public static void main(String[] args) throws Exception { // 生成2个user对象 User u1 = new User("01","张三",10000f,"中国"); User u2 = new User("02","李四",2000f,"日本"); DataOutputStream dos = new DataOutputStream(new FileOutputStream("d:/user.dat")); dos.writeUTF(u1.getId()); dos.writeUTF(u1.getName()); dos.writeFloat(u1.getSal()); dos.writeUTF(u1.getAddr()); dos.writeUTF(u2.getId()); dos.writeUTF(u2.getName()); dos.writeFloat(u2.getSal()); dos.writeUTF(u2.getAddr()); // 读取存入到文件中的内容 DataInputStream dis = new DataInputStream(new FileInputStream("d:/user.dat")); String u1_id = dis.readUTF(); String u1_name = dis.readUTF(); float u1_sal = dis.readFloat(); String u1_addr = dis.readUTF(); User user1 = new User(u1_id,u1_name,u1_sal,u1_addr); User user2 = new User(dis.readUTF(),dis.readUTF(),dis.readFloat(),dis.readUTF()); System.out.println(user1); System.out.println(user2); } }DataStreamDemo.java
标签:Java,String,u1,BigData,id,DataInputStream,User,public,name 来源: https://www.cnblogs.com/OliverQin/p/12114157.html