博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

10java进阶——IO2

Posted on 2019-02-04 10:56  心默默言  阅读(348)  评论(0编辑  收藏  举报

1. Properties类

Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。

特点:

  1. Hashtable的子类,map集合中的方法都可以用。
  2. 该集合没有泛型。键值都是字符串。
  3. 它是一个可以持久化的属性集。键值可以存储到集合中,也可以存储到持久化的设备(硬盘、U盘、光盘)上。键值的来源也可以是持久化的设备。
  4. 有和流技术相结合的方法。
  • load(InputStream)  把指定流所对应的文件中的数据,读取出来,保存到Propertie集合中
  • store(OutputStream,commonts)把集合中的数据,保存到指定的流所对应的文件中,参数commonts代表对描述信息

package cn.jxufe.java.chapter09.demo05;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;

/*
 *  集合对象Properties类,继承Hashtable,实现Map接口
 *  可以和IO对象结合使用,实现数据的持久存储
 */
public class Test01Property {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        System.out.println("使用Properties集合,存储键值对:");
        function();
        System.out.println("\nProperties集合特有方法 load:");
        function_1();
        System.out.println("\nProperties集合的特有方法store:");
        function_2();

    }

    /*
     * Properties集合的特有方法store
     * store(OutputStream out)
     * store(Writer w)
     * 接收所有的字节或者字符的输出流,将集合中的键值对,写回文件中保存
     */
    public static void function_2() throws IOException {
        Properties properties = new Properties();
        properties.setProperty("name", "zhaosi");
        properties.setProperty("age", "31");
        properties.setProperty("email", "13657914425@163.com");

        // 键值对,存回文件,使用集合的方法store传递字符输出流
        FileWriter fr = new FileWriter("d:\\pro.properties");
        properties.store(fr, "byZhao");

    }

    /*
     * Properties集合特有方法 load
     * load(InputStream in)
     * load(Reader r)
     * 传递任意的字节或者字符输入流
     * 流对象读取文件中的键值对,保存到集合
     */
    public static void function_1() throws IOException {
        Properties properties = new Properties();
        FileReader fileReader = new FileReader("d:\\pro.properties");
        // 调用集合的方法load,传递字符输入流
        properties.load(fileReader);
        fileReader.close();
        System.out.println(properties);
    }

    /*
     * 使用Properties集合,存储键值对
     * setProperty等同与Map接口中的put
     * setProperty(String key, String value)
     * 通过键获取值, getProperty(String key)
     */
    public static void function() {
        Properties properties = new Properties();
        properties.setProperty("a", "1");
        properties.setProperty("b", "2");
        properties.setProperty("c", "3");
        System.out.println(properties);

        String value = properties.getProperty("a");
        System.out.println(value);
        // 方法stringPropertyNames,将集合中的键存储到Set集合,类似于Map接口的方法keySet
        Set<String> set = properties.stringPropertyNames();
        for (String key : set) {
            System.out.println(key + "  " + properties.getProperty(key));
        }
    }
}

2.序列化流与反序列化流

用于从流中读取对象的

操作流 ObjectInputStream    称为 反序列化流

用于向流中写入对象的操作流 ObjectOutputStream   称为 序列化流

特点:用于操作对象。可以将对象写入到文件中,也可以从文件中读取对象。

 

2.1实例

package cn.jxufe.java.chapter09.demo05;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Test02ObjectStream {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // TODO Auto-generated method stub
        writeObject();
        readObject();
    }

    /*
     * ObjectInputStream
     * 构造方法:ObjectInputStream(InputStream in)
     * 传递任意的字节输入流,输入流封装文件,必须是序列化的文件
     * Object readObject()  读取对象
     */
    public static void readObject() throws IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream("d:\\person.txt");
        // 创建反序列化流,构造方法中,传递字节输入流
        ObjectInputStream ois = new ObjectInputStream(fis);
        // 调用反序列化流的方法 readObject()读取对象
        Object object = ois.readObject();// ClassNotFoundExcept,因为要有person.class文件
        System.out.println(object);
        ois.close();
    }

    /*
     * ObjectOutputStream
     * 构造方法: ObjectOutputStream(OutputSteam out)
     * 传递任意的字节输出流
     * void writeObject(Object obj)写出对象的方法
     */
    public static void writeObject() throws IOException {
        // 创建字节输出流,封装文件
        FileOutputStream fos = new FileOutputStream("d:\\person.txt");
        // 创建写出对象的序列化流的对象,构造方法传递字节输出流
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        Person person = new Person("lisi", 20);

        oos.writeObject(person);
        oos.close();

    }
}

class Person implements Serializable {
    public String name;
    public int age;
//    public transient int age;/*transient阻止成员变量序列化*/
    // 类,自定义了序列号,编译器不会计算序列号
//    private static final long serialVersionUID = 1478652478456L;

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public Person() {
    }

    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 "Person [name=" + name + ", age=" + age + "]";
    }

}

2.2静态不能序列化

package cn.jxufe.java.chapter09.demo05;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Test02ObjectStream {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // TODO Auto-generated method stub
//        writeObject();
        readObject();
    }

    /*
     * ObjectInputStream
     * 构造方法:ObjectInputStream(InputStream in)
     * 传递任意的字节输入流,输入流封装文件,必须是序列化的文件
     * Object readObject()  读取对象
     */
    public static void readObject() throws IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream("d:\\person.txt");
        // 创建反序列化流,构造方法中,传递字节输入流
        ObjectInputStream ois = new ObjectInputStream(fis);
        // 调用反序列化流的方法 readObject()读取对象
        Object object = ois.readObject();// ClassNotFoundExcept,因为要有person.class文件
        System.out.println(object);
        ois.close();
    }

    /*
     * ObjectOutputStream
     * 构造方法: ObjectOutputStream(OutputSteam out)
     * 传递任意的字节输出流
     * void writeObject(Object obj)写出对象的方法
     */
    public static void writeObject() throws IOException {
        // 创建字节输出流,封装文件
        FileOutputStream fos = new FileOutputStream("d:\\person.txt");
        // 创建写出对象的序列化流的对象,构造方法传递字节输出流
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        Person person = new Person("lisi", 19);

        oos.writeObject(person);
        oos.close();

    }
}

class Person implements Serializable {
    public String name;
//    public  int age;
    public static int age;
//    public transient int age;/*transient阻止成员变量序列化*/
    // 类,自定义了序列号,编译器不会计算序列号
//    private static final long serialVersionUID = 1478652478456L;

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public Person() {
    }

    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 "Person [name=" + name + ", age=" + age + "]";
    }

}

注:此处的序列化是针对对象的,而静态成员是属于类的,所以不能序列化。

2.3序列化接口

当一个对象要能被序列化,这个对象所属的类必须实现Serializable接口。否则会发生异常NotSerializableException异常。

同时当反序列化对象时,如果对象所属的class文件在序列化之后进行的修改,那么进行反序列化也会发生异常InvalidClassException。发生这个异常的原因如下:

  • 该类的序列版本号与从流中读取的类描述符的版本号不匹配
  • 该类包含未知数据类型
  • 该类没有可访问的无参数构造方法

Serializable标记接口。该接口给需要序列化的类,提供了一个序列版本号。serialVersionUID. 该版本号的目的在于验证序列化的对象和对应类是否版本匹配。

2.4序列化数组

package cn.jxufe.java.chapter09.demo05;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test03ObjectStreamForArray {

    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        // TODO Auto-generated method stub
        int[] numbers = { 1, 2, 3, 4, 5 };
        String[] strings = { "John", "Susan", "Kim" };
        try (ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("d:\\array.dat", true));) {
            output.writeObject(numbers);
            output.writeObject(strings);

        }
        try (ObjectInputStream input = new ObjectInputStream(new FileInputStream("d:\\array.dat"));) {
            int[] newNumbers = (int[]) (input.readObject());
            String[] newStrings = (String[]) (input.readObject());
            for (int number : newNumbers) {
                System.out.print(number + " ");
            }
            System.out.println();

            for (String string : newStrings) {
                System.out.print(string + " ");
            }

        }
    }

}

3. 打印流

3.1打印流的概述

打印流添加输出数据的功能,使它们能够方便地打印各种数据值表示形式.

打印流根据流的分类:

  • 字节打印流  PrintStream
  • 字符打印流  PrintWriter

方法:

  • void print(String str): 输出任意类型的数据,
  • void println(String str): 输出任意类型的数据,自动写入换行操作
package cn.jxufe.java.chapter09.demo05;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

/*
 *  打印流
 *    PrintStream
 *    PrintWriter
 *  打印流的特点:
 *   1. 此流不负责数据源,只负责数据目的
 *   2. 为其他输出流,添加功能
 *   3. 永远不会抛出IOException
 *      但是,可能抛出别的异常
 *   
 *   两个打印流的方法,完全一致
 *    构造方法,就是打印流的输出目的端
 *    PrintStream
 *       构造方法,接收File类型,接收字符串文件名,接收字节输出流OutputStream
 *    PrintWriter  
 *       构造方法,接收File类型,接收字符串文件名,接收字节输出流OutputStream, 接收字符输出流Writer
 *   
 */
public class Test04PrintWriter {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        function();
        function_1();
        function_2();
    }

    /*
     * 打印流,输出目的,是流对象
     * 可以是字节输出流,可以是字符的输出流
     * OutputStream  Writer
     */
    public static void function_2() throws IOException {
        FileOutputStream fos = new FileOutputStream("d:\\3.txt");
        OutputStreamWriter output = new OutputStreamWriter(fos, "utf-8");
        PrintWriter pw = new PrintWriter(output);
        pw.println("打印流");
        pw.close();
    }

    /*
     * 打印流,输出目的,String文件名
     */
    public static void function_1() throws FileNotFoundException {
        PrintWriter pw = new PrintWriter("d:\\2.txt");
        pw.println(3.5);
        pw.close();
    }

    /*
     * 打印流,向File对象的数据目的写入数据
     * 方法print println  原样输出
     * write方法走码表
     */
    public static void function() throws FileNotFoundException {
        File file = new File("d:\\1.txt");
        PrintWriter printWriter = new PrintWriter(file);
        printWriter.print(true);
        printWriter.print(100);
        printWriter.close();
    }

}

3.2打印流完成数据自动刷新

可以通过构造方法,完成文件数据的自动刷新功能

构造方法:

开启文件自动刷新写入功能

  • public PrintWriter(OutputStream out, boolean autoFlush)
  • public PrintWriter(Writer out, boolean autoFlush)
package cn.jxufe.java.chapter09.demo05;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class Test05PrintWriter {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        function();
    }

    /* 
     * 打印流,可以开启自动刷新功能
     * 满足2个条件:
     *   1. 输出的数据目的必须是流对象
     *       OutputStream  Writer
     *   2. 必须调用println,printf,format三个方法中的一个,启用自动刷新
     */
    public static void function() throws IOException {
        // File f = new File("XXX.txt");
        FileOutputStream fos = new FileOutputStream("d:\\4.txt");
        PrintWriter pw = new PrintWriter(fos, true); //true 开启自动刷新
        pw.println("i");
        pw.println("love");
        pw.println("java");
        pw.close();
    }
}

3.3文件复制

package cn.jxufe.java.chapter09.demo05;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/*
 * 打印流实现文本复制
 *   读取数据源  BufferedReader+File 读取文本行
 *   写入数据目的 PrintWriter+println 自动刷新
 */
public class Test06PrintWriterCopy {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        BufferedReader bfr = new BufferedReader(new FileReader("c:\\a.txt"));
        PrintWriter pw = new PrintWriter(new FileWriter("d:\\a.txt"), true);
        String line = null;
        while ((line = bfr.readLine()) != null) {
            pw.println(line);
        }
        pw.close();
        bfr.close();
    }

}