一:操作基本数据类型的流
DataInputStream 字符输入流,读取数据
DataOutputStream 字符输出流,写入数据
//读的顺序与写顺序一致
public class DataInputStreamDemo1 {
public static void main(String[] args) throws IOException {
write();
read();
}
private static void read() throws FileNotFoundException, IOException {
DataInputStream dis = new DataInputStream(new FileInputStream("b3.txt"));
byte b = dis.readByte();
System.out.println(b);
short s = dis.readShort();
System.out.println(s);
int i = dis.readInt();
System.out.println(i);
long l = dis.readLong();
System.out.println(l);
float f = dis.readFloat();
System.out.println(f);
double d = dis.readDouble();
System.out.println(d);
char ch = dis.readChar();
System.out.println(ch);
boolean bb = dis.readBoolean();
System.out.println(bb);
dis.close();
}
private static void write() throws IOException {
DataOutputStream dos = new DataOutputStream(new FileOutputStream("b3.txt"));
dos.writeByte(1);
dos.writeShort(20);
dos.writeInt(300);
dos.writeLong(4000);
dos.writeFloat(12.34f);
dos.writeDouble(12.56);
dos.writeChar('a');
dos.writeBoolean(true);
dos.close();
}
}
二、序列化
序列化:把对象按照流一样的方式存到文本文件或者数据库或者在网络中传输
对象 -- 流数据: ObjectOutputStream
反序列化:把文本文件中的流对象数据或者网络中的流数据还原成一个对象
流数据 -- 对象: ObjectInputStream
注意:(1)对象类中要实现Serializable接口
(2) 当写入数据后,然后对对象类做了修改,在进行读时会报错,因为Serializable是一个标记接口,会生成一个标记值,写入后,在读的时候,因为对象类做了修改标记值发生改变,会报错,所以可以给对象类一个设定一个标记值,怎样修改类都能读到;
(3)如果有变量不想让外界获取,可以用transient修饰变量
public class Student implements Serializable {
private static final long serialVersionUID = -1639600841900718407L;//设定的标记值
private String name;
private transient int age;//transient修饰可以不被读到,结果显示默认值
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Test1 {
public static void main(String[] args) {
try {
// write();
read();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void write() throws Exception {
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("aa.txt"));
Student s=new Student("张国庆",12);
oos.writeObject(s);
}
public static void read() throws Exception {
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("aa.txt"));
System.out.println(ois.readObject());
}
}
Student{name='张国庆', age=0}
三、Properties集合
Properties作为Map集合的使用,可以输出对应的值
Properties properties = new Properties();
properties.setProperty("user", "root");
properties.setProperty("password", "123456");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
System.out.println(user + "--" + password);
root--123456