import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;public class DataOutputStream1 {public static void main(String[] args) {//创建一个数据输出流包装一个低级的字节输出流try (DataOutputStream dos=new DataOutputStream(new FileOutputStream("D:\\code\\weilai1\\src\\itheima.txt"));){dos.writeInt(97);dos.writeByte(99);dos.writeChar('中');dos.writeDouble(99.9);dos.writeUTF("世界,你好");} catch (Exception e) {e.printStackTrace();}}
}
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;public class DataInputStream1 {public static void main(String[] args) {try ( DataInputStream dis= new DataInputStream (new FileInputStream("D:\\code\\weilai1\\src\\itheima.txt"))){int a=dis.readInt();System.out.println(a);byte b=dis.readByte();System.out.println(b);char c= dis.readChar();System.out.println(c);double d= dis.readDouble();System.out.println(d);String rs= dis.readUTF();System.out.println(rs);} catch (Exception e) {e.printStackTrace();}}
}
序列化流
对象序列化:把对象写到Java文件中去
对象反序列化:把文件中的Java对象读出来
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;public class ObjectOutputStream1 {public static void main(String[] args) {try( ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("D:\\code\\weilai1\\src\\itheima1.txt"));) {//创建一个Java对象ObjectUser user=new ObjectUser("admin","zhangsan",26,"12345678");oos.writeObject(user);System.out.println("对象序列化成功了");} catch (Exception e) {e.printStackTrace();}}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;public class ObjectIntputStream1 {public static void main(String[] args) {try ( ObjectInputStream ois=new ObjectInputStream(new FileInputStream("D:\\code\\weilai1\\src\\itheima1.txt"));){ObjectUser ou=(ObjectUser) ois.readObject();System.out.println(ou);} catch (Exception e) {e.printStackTrace();}}
}
import java.io.Serializable;
//注意:对象如果需要序列化,必须实现序列化接口
public class ObjectUser implements Serializable {private String loginname;private String username;private int age;//transient 这个成员变量将不参与序列化private transient String password;public ObjectUser() {}public ObjectUser(String loginname, String username, int age, String password) {this.loginname = loginname;this.username = username;this.age = age;this.password = password;}public String getLoginname() {return loginname;}public void setLoginname(String loginname) {this.loginname = loginname;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "ObjectUser{" +"loginname='" + loginname + '\'' +", username='" + username + '\'' +", age=" + age +", password='" + password + '\'' +'}';}
}