学习Java的第15天
总结:节点流也就是文件流,实例化的时候构造器的参数列表中要传入目标文件(也就是数据源的地址 这个地址分为相对地址和绝对地址)其中处理流的构造器参数列表中要传入节点流
1.对象流
-
对象的流的使用:
-
OOS和OIS
-
作用:存取和读取基本数据类型或对象的处理流。可以将Java中的对象转化为二进制流。
-
一个类可以实例化的要求:
-
实现接口:Serializable
-
当前类提供一个全局常量作为标识:SerializableUID
-
除了当前类实现**接口外,还必须保证其内部接口也是先接口
-
OOS OBS 不能序列化static 和 transient修饰的成员变量
public class Person implements Serializable { //要想进行序列化的类必须实现Serializable接口 //定义一个全局常量UId (用于表示) //并且它的所有属性必须是实现了**接口的 public static final Long SerializableUId = 21321312312L; private int age; @Override public String toString() { return "Person{" + "age=" + age + ", name='" + name + '\'' + '}'; } public Person(int age, String name) { this.age = age; this.name = name; } private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
public class ObjectInputOutputObjectTest { @Test public void test1() { ObjectOutputStream oos = null; try { //对象的序列化操作 oos = new ObjectOutputStream(new FileOutputStream("hello.dat")); // oos.writeBytes("我爱北京天安门 天安门是我的家"); // oos.flush();//刷新操作 oos.writeObject(new Person(12, "小米")); oos.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (oos != null) { try { oos.close(); } catch (IOException e) { e.printStackTrace(); } finally { } } } } @Test public void test() { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("hello.dat")); //反序列化操作 Person person = (Person) ois.readObject(); System.out.println(person); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (ois != null) { try { ois.close(); } catch (IOException e) { e.printStackTrace(); } finally { } } } } }
-
-
-
随机存取文件流
-
RandomAccessFile的使用
-
直接继承于object类,实现了DataInput和DateOutput接口。
-
可以既作为输入流有作为输出流。
/* 利用随机存取文件流实现文件的插入操作 */ public void test1() throws IOException { RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw"); //1.通过实例化将hello.txt文件设置为读写模式 这个文件是一个输入输出流 raf1.seek(3); //2.默认指针是在0的位置进行覆盖操作 现在调节到3的位置 StringBuilder builder = new StringBuilder((int)new File("hello1.txt").length()); //3.将指针后面的元素先保存到字符数组中 byte[] buffer = new byte[20]; //4.定义一个字节数组 每次读取20个字节放到字符数组中 int len; while ((len= raf1.read(buffer)) != -1){ //从一个**输入流**中读取一定数量的字节,并将这些字节存储到其缓冲作用的数组b中 builder.append(new String(buffer,0,len)); } //5.调回指针 写入xyz builder raf1.seek(3); raf1.write("xyz".getBytes()); raf1.write(buffer.toString().getBytes()); //6.将字符数组转换为字符串 转换为字节 加入 } }
-