public static void write() throws IOException {
OutputStream os = new FileOutputStream("E:/z/tt1.txt");
BufferedOutputStream bos = new BufferedOutputStream(os);
ObjectOutputStream dos = new ObjectOutputStream(bos);
dos.writeInt(10);
dos.writeDouble(3.14);
dos.writeChars("学习");
dos.writeBoolean(false);
dos.writeUTF("abcde");
dos.close();
}
public static void read() throws IOException, ClassNotFoundException {
InputStream is = new FileInputStream("E:/z/tt1.txt");
BufferedInputStream bis = new BufferedInputStream(is);
ObjectInputStream dis = new ObjectInputStream(bis);
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readChar());
//System.out.println(dis.readChar());
System.out.println(dis.readBoolean());
System.out.println(dis.readUTF());
}
}
保存的时候要转换为UTF-8编码,其实这种用法比较少,一般保存JavaBean,用writeobject方法保存。
你这样子是用了几种编码方式往文件里写东西了
dos.writeChars("学习");
char占2个字节,按照2个字节的方式写入文件中。
dis.readUTF()读取的时候,是按照字符串进行读取的,由于writeChars写入的内容,没有用对应的方法读出,被dis.readUTF()读取到的时候,会读到已经结束的位置之后,导致报eof异常。