🌈键盘敲烂,年薪30万🌈
目录
一、序列化流 (对象操作流)
二、打印流
三、压缩流(zip文件)
四、转换流
一、序列化流 (对象操作流)
序列化的概念:
当不想让他人读懂文件里的数据时,可以将数据序列化
创建一个自定义对象时,会根据所有成员计算出一个序列号。
存储数据时,会先根据序列号序列化内容,然后把序列号和被序列内容一同存到文件里面。
//序列化流
Studen s = new Studen("xiaohong", 14);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("10_16\\a.txt"));
oos.writeObject(s);
oos.close();
//反序列化输入流
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("10_16\\a.txt"));
Object o = ois.readObject();
ois.close();
System.out.println(((Studen) o));
代码解析:
要关联基本流别忘了关流
细节:
①要序列化的类必须实现Serializable接口,该接口是标记性接口,里面没有抽象方法,作用就是标识这个类可被序列化和反序列化
②如果我们存完该类后,又修改了该类的成员,序列号就会变,序列号变也就意味着以前的序列号没用了,你在反序列化就会报错,在该类中添加以下代码。
private static final long serialVersionUID = -1326719789726226251L;
③反序列化出来的数据类型是Object,我们要强转为需要的类型
用集合序列化多个对象
如果我们在存储一个类的多个对象是,在反序列化时读取到最后一个就会错,EOFExpection异常,所以 一般我们用集合存储多个对象,直接序列化和反序列化集合
二、打印流
PrintStream ps = new PrintStream(new FileOutputStream("10_16\\a.txt"));
ps.println("BBB");
ps.close();
代码分析:
关联基本流
使用print、printfln等方法向文件写数据
关流
标准输出流
System.out.printfln就是标准输出流,输出到控制台。
System是系统的一个类.out一个静态的输出流,默认指向控制台,所以这也是为什么我们每次打印都能在控制台看到数据
三、压缩流(zip文件)
解压缩本质:从压缩文件读取数据,每一个ZipEntery对象代表一个压缩文件或文件夹
File src = new File("10_16\\a.zip");
File dest = new File("10_16\\");
unzip(src, dest);
private static void unzip(File src, File dest) throws IOException {
ZipInputStream zip = new ZipInputStream(new FileInputStream(src), Charset.forName("GBK"));//nextEntry表示压缩包里面的每一个文件,读取完返回nullZipEntry ze = null;while((ze = zip.getNextEntry()) != null){//如果是文件夹 创建文件夹if(ze.isDirectory()){new File(dest, ze.toString()).mkdir();}else{int tmp = 0;FileOutputStream fos = new FileOutputStream(new File(ze.toString()));while((tmp = zip.read()) != -1){fos.write(tmp);}fos.close();}}zip.close();}
压缩实际:将数据写入到压缩文件,将压缩文件对象放到压缩包里
//压缩文件流File src = new File("10_16\\a");File dest = new File(src.getParent(), src.getName()+".zip");//将文件写入压缩文件流ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest));//第三个参数代表压缩包里面的路径//注意第三个参数toZip(src, zos, src.getName());zos.close();private static void toZip(File src, ZipOutputStream zos, String dest) throws IOException {//files是绝对路径File[] files = src.listFiles();for (File file : files) {if(file.isDirectory()){toZip(file, zos, dest+"\\"+file.getName());}else{//将文件写入到entryzip对象里,将此对象put到压缩包里ZipEntry ze = new ZipEntry(dest+"\\"+file.getName());zos.putNextEntry(ze);FileInputStream fis = new FileInputStream(file);int tmp = 0;while((tmp = fis.read()) != -1){zos.write(tmp);}fis.close();zos.closeEntry();}}}
四、转换流
是字符流与字节流之间的桥梁
InputStreamReader:将一个输入字节流转换为字符流(读数据的时候可以读一个字符)
OutputSreamWriter:将一个输出字符流转为字节流(写数据的时候写一个字节)
//将字节流转换为字符流File newfile = new File("IOTest1\\a.txt");InputStreamReader isr = new InputStreamReader(new FileInputStream(newfile));int tmp = 0;while ((tmp = isr.read()) != -1){System.out.print((char)tmp);}isr.close();
File newfile = new File("IOTest1\\a.txt");OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(newfile));osw.write("我是通过转换流写入的");osw.close();