• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
tyrantblue
博客园    首页    新随笔    联系   管理    订阅  订阅
Java学习笔记(七点五)集合IO案例和特殊操作流

学习笔记7.5

集合IO案例

案例1. 集合到文件

需求:把ArrayList集合中的字符串数据写到文本文件。要求:每一个字符串元素作为文件的一行数据

package com;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class collection_io_demo {

    public static void main(String[] args) throws IOException {

        //创建ArrayList和BufferedWriter对象
        ArrayList<String> array = new ArrayList<>();
        BufferedWriter bw = new BufferedWriter(new FileWriter("基础语法\\src\\goods\\miku001.txt"));

        //添加元素
        array.add("hello");
        array.add("world");
        array.add("java");
        array.add("ayaka");

        //写入数据
//        for (int i = 0; i < array.size(); i++) {
//            bw.write(array.get(i));
//            bw.newLine();
//            bw.flush();
//        }

        //增强for
        for (String s : array){
            bw.write(s);
            bw.newLine();
            bw.flush();
        }

        //释放资源
        bw.close();

    }
}

案例2. 文件到集合

需求:把文本文件中的数据读取到集合中,并遍历集合。要求:文件中每一行数据是一个集合元素

package com.collection_io_demo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.Buffer;
import java.util.ArrayList;
import java.util.Iterator;

public class Collection_Io_Demo02 {

    public static void main(String[] args) throws IOException {

        //创建ArrayList集合对象和字符缓冲输入流BufferedReader对象
        ArrayList<String> array = new ArrayList<>();
        BufferedReader br = new BufferedReader(new FileReader("基础语法\\src\\goods\\miku001.txt"));

        //读数据
        String s;
        while((s =br.readLine()) != null){
            array.add(s);
        }

        //增强for
        for (String s1 : array){
            System.out.println(s1);
        }

        //Iterator
        Iterator<String> iterator = array.iterator();
        while (iterator.hasNext()){
            String s2 = iterator.next();
            System.out.println(s2);
        }
        
        //释放资源
        br.close();

    }
}

案例3. 点名器

需求:我有一个文件里面存储了班级同学的姓名,每一个姓名占一行,要求通过程序实现随机点名器

package com.collection_io_demo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

public class Collection_Io_Demo03 {

    public static void main(String[] args) throws IOException {

        //创建ArrayList集合对象和字符缓冲输入流BufferedReader对象
        ArrayList<String> array = new ArrayList<>();
        BufferedReader br = new BufferedReader(new FileReader("基础语法\\src\\goods\\NameBook.txt"));

        //读数据
        String str;
        while((str = br.readLine()) != null){

            //添加进ArrayList集合对象
            array.add(str);

        }

        //随机数
        Random r = new Random();
        int ran = r.nextInt(array.size());
        String s = array.get(ran);
        System.out.println("幸运儿:" + s);

        //释放资源
        br.close();
    }
}

案例4. 集合到文件(改进版)

需求:把ArrayList集合中的学生数据写入到文本文件,要求:每一个学生对象的数据作为文件的一行数据

格式:学号,姓名,年龄,居住地

package com.collection_io_demo;

public class Student {
    private String no;
    private String name;
    private int age;
    private String home;

    public Student(String no, String name, int age, String home) {
        this.no = no;
        this.name = name;
        this.age = age;
        this.home = home;
    }

    public Student() {
    }

    public String getNo() {
        return no;
    }

    public void setNo(String no) {
        this.no = no;
    }

    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;
    }

    public String getHome() {
        return home;
    }

    public void setHome(String home) {
        this.home = home;
    }
}
package com.collection_io_demo;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class Collection_Io_Demo04 {

    public static void main(String[] args) throws IOException {

        //创建集合对象
        ArrayList<Student> array = new ArrayList<>();

        //创建学生对象
        Student s1 = new Student("ty001", "张三", 23 , "北京");
        Student s2 = new Student("ty002", "李四", 24 , "上海");
        Student s3 = new Student("ty003", "王五", 25 , "广州");
        Student s4 = new Student("ty004", "刘陆", 26 , "深圳");

        //添加元素
        array.add(s1);
        array.add(s2);
        array.add(s3);
        array.add(s4);

        //创建字符缓冲输出流对象
        BufferedWriter bw = new BufferedWriter(new FileWriter("基础语法\\src\\goods\\miku001.txt"));

        //写数据
        for (Student s : array) {
//            bw.write(s.getNo() + ",");
//            bw.flush();
//            bw.write(s.getName() + ",");
//            bw.flush();
//            bw.write(s.getAge() + ",");//有String别的类型就会转为String类型
//            bw.flush();
//            bw.write(s.getHome());
//            bw.flush();
//            bw.newLine();

            //字符串拼接
            StringBuilder sb = new StringBuilder();
            sb.append(s.getNo()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getHome());
            bw.write(sb.toString());
            bw.newLine();
            bw.flush();
        }

        //释放资源
        bw.close();
    }
}

案例5. 文件到集合(改进版)

需求:把文本文件中的数据读取到集合中,并遍历集合。要求:文件中的每一行数据是一个学生对象的成员变量值

package com.collection_io_demo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Collectiom_Io_Demo05 {

    public static void main(String[] args) throws IOException {

        //创建集合对象
        ArrayList<Student> array = new ArrayList<>();

        //创建学生对象

        //创建字符缓冲输入流对象
        BufferedReader br = new BufferedReader(new FileReader("基础语法\\src\\goods\\miku001.txt"));

        //读数据
        String str;
        while ((str = br.readLine()) != null){

            //分割数组
            String[] sp = str.split(",");//split()切割

            //向集合中添加数据
            Student s = new Student(sp[0],sp[1],Integer.parseInt(sp[2]),sp[3]);
            array.add(s);

        }

        //输出
        for (Student s : array){
            StringBuilder sb = new StringBuilder();
            sb.append(s.getNo()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getHome());
            System.out.println(sb.toString());
        }

        //释放资源
        br.close();
    }
}

案例6. 集合到文件数据改进版

需求:键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),要求按照成绩总分从高到低写入文本文件

格式:姓名,语文成绩,数学成绩,英语成绩

package com.collection_io_demo;

public class StudentScore{
    private String name;
    private int chinese;
    private int math;
    private int english;

    public StudentScore() {
    }

    public StudentScore(String name, int chinese, int math, int english) {
        this.name = name;
        this.chinese = chinese;
        this.math = math;
        this.english = english;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getChinese() {
        return chinese;
    }

    public void setChinese(int chinese) {
        this.chinese = chinese;
    }

    public int getMath() {
        return math;
    }

    public void setMath(int math) {
        this.math = math;
    }

    public int getEnglish() {
        return english;
    }

    public void setEnglish(int english) {
        this.english = english;
    }

    public int getAll(){

        int sum = this.chinese+this.math+this.english;
        return sum;

    }
}
package com.collection_io_demo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Collection_Io_Demo05 {

    public static void main(String[] args) throws IOException {

        //创建集合对象
        ArrayList<Student> array = new ArrayList<>();

        //创建学生对象

        //创建字符缓冲输入流对象
        BufferedReader br = new BufferedReader(new FileReader("基础语法\\src\\goods\\miku001.txt"));

        //读数据
        String str;
        while ((str = br.readLine()) != null){

            //分割数组
            String[] sp = str.split(",");//split()切割

            //向集合中添加数据
            Student s = new Student(sp[0],sp[1],Integer.parseInt(sp[2]),sp[3]);
            array.add(s);

        }

        //输出
        for (Student s : array){
            StringBuilder sb = new StringBuilder();
            sb.append(s.getNo()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getHome());
            System.out.println(sb.toString());
        }

        //释放资源
        br.close();
    }
}

案例7. 复制单级文件夹

需求:把一个文件夹及目录下的文件(无其他文件夹)复制到另一个目录

package com.collection_io_demo;

import java.io.*;

public class Collection_Io_Demo07 {

    public static void main(String[] args) throws IOException {

        //创建文件对象
        File src = new File("基础语法\\src\\AnimeCopy");

        //获取文件名
        String srcName = src.getName();

        //创建目的地File对象
        File goal = new File("基础语法\\src\\goods\\",srcName);

        //判断是否存在目的地
        if (!goal.exists()) {
            goal.mkdir();//创建目录
        }

        //获取创建文件数组
        File[] files = src.listFiles();

        //根据文件数组创建文件
        for (File f : files){
            String fn = f.getName();
            File file = new File(goal, fn);
/*
            //创建字节缓冲输入流对象
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));

            //创建字节缓冲输出流对象
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));

            //一次读一个字节数组
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1){
                bos.write(bytes,0,len);
                bos.flush();
            }

            //释放资源
            bos.close();
            bis.close();
*/
            copyFile(f,file);

        }

    }

    //将文件复制功能封装成一个方法
    public static void copyFile(File ago,File now) throws IOException{
        //创建字节缓冲输入流对象
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(ago));

        //创建字节缓冲输出流对象
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(now));

        //一次读一个字节数组
        byte[] bytes = new byte[1024];
        int len;
        while ((len = bis.read(bytes)) != -1){
            bos.write(bytes,0,len);
            bos.flush();
        }

        //释放资源
        bos.close();
        bis.close();
    }
}

案例8. 复制多级文件夹

需求:把一个多级文件夹复制到别的地方

package com.collection_io_demo;

import java.io.*;

public class Collection_Io_Demo08 {

    //复制多级文件夹
    public static void main(String[] args) throws IOException{

        //创建源目录File对象
        File src = new File("基础语法\\src\\goods");

        //获取目录文件名
        String srcName = src.getName();

        //创建目标目录File对象
        File goal = new File("基础语法", srcName);

        //判断目录是否存在
        if(!goal.exists()){
            goal.mkdir();
        }

        //递归复制目录和文件
        dgCopy(src,goal);
    }

    //file1为原目录,file2为复制目录
    public static void dgCopy(File file1,File file2) throws IOException{

        //创建文件目录
        file2.mkdir();

        File[] files = file1.listFiles();

        //判断目录是否为空
        if (files != null) {

            for (File f : files){

                //如果是目录则调用dg(File file) 方法
                if (f.isDirectory()){
                    dgCopy(f,new File(file2,f.getName()));
                } else if (f.isFile()){

                    //为文件则直接复制
                    copyFile(f,new File(file2,f.getName()));

                }
            }
        }
    }

    //复制f1到f2
    public static void copyFile(File f1,File f2) throws IOException {

        //创建字节缓冲输入流
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f1));

        //创建字节缓冲输出流
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f2));

        //读数据 一次一个字节数组
        byte[] bytes = new byte[1024];
        int len;
        while ((len = bis.read(bytes)) != -1){

            //写数据
            bos.write(bytes,0,len);
            bos.flush();
        }

        //释放资源
        bis.close();
        bos.close();
    }
}

复制文件的异常处理

package com.collection_io_demo;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Collection_Io_Exception_Demo08 {

    //复制文件加入异常处理
    public static void main(String[] args) throws IOException {

        method1();

    }

    //JDK7改进方案
    public static void method3() {

        try(//文件缓冲输入流
            FileReader fr = new FileReader("基础语法\\src\\goods\\miku001.txt");
            //文件缓冲输出流
            FileWriter fw = new FileWriter("基础语法\\src\\goods\\miku001.txt");) {

            //读数据
            char[] chars = new char[1024];
            int len;
            while ((len = fr.read(chars)) != -1){

                //写数据
                fw.write(chars,0,len);
            }
        } catch (IOException e){
            e.printStackTrace();
        }

        //自动释放资源
    }

    //try...catch...finally
    public static void method2(){

        FileReader fr = null;
        FileWriter fw = null;

        try{
            //文件缓冲输入流
            fr = new FileReader("基础语法\\src\\goods\\miku001.txt");

            //文件缓冲输出流
            fw = new FileWriter("基础语法\\src\\goods\\miku001.txt");

            //读数据
            char[] chars = new char[1024];
            int len;
            while ((len = fr.read(chars)) != -1){

                //写数据
                fw.write(chars,0,len);
            }
        } catch (IOException e) {

            e.printStackTrace();

        } finally {
            //释放资源
            if (fr != null){
                try {
                    fr.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if (fw != null){
                try {
                    fw.close();
                } catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    //抛出处理
    public static void method1() throws IOException {
        //文件缓冲输入流
        FileReader fr = new FileReader("基础语法\\src\\goods\\miku001.txt");

        //文件缓冲输出流
        FileWriter fw = new FileWriter("基础语法\\src\\goods\\miku001.txt");

        //读数据
        char[] chars = new char[1024];
        int len;
        while ((len = fr.read(chars)) != -1){

            //写数据
            fw.write(chars,0,len);
        }

        //释放资源
        fr.close();
        fw.close();
    }
}

特殊操作流

1. 标准输入输出流

System类中有两个静态的成员变量:

  • public static final InputStream in:标准输入流。通常该流对应于键盘输入或由主机环境或用户指定的另一个输入源
  • public static final PrintStream out:标准输出流。通常该流对应于显示输出或由主机环境或用户指定的另一个输出目标

自己实现键盘录入数据:

  • BufferedReader br = new BufferdeReader(new inputStreamReader(System.in));

写起来麻烦,Java就提供了一个类实现键盘录入

  • Scanner sc = new Scanner(System.in);

输出语句的本质:是一个标准的输出流

  • PrintStream ps = System.out;
  • PrintStream 类中有的方法,system.out 都可以使用

示例代码:

package com.io;

import javax.imageio.IIOException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;

public class SystemInDemo01 {

    //标准输入输出流
    public static void main(String[] args) throws IOException {

        //public static final IntputStream in:标准输入流
        //InputStream is = System.in;

        //一次读一个字节数组
//        int by;
//        while((by = is.read()) != -1){
//            System.out.print((char)by);
//        }

        //InputStreamRead:转换流
        //InputStreamReader isr = new InputStreamReader(System.in);
        //一次读一行
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("请输入一行字符串:");

        String str;
        while ((str = br.readLine()) != null){
            System.out.print("你输入的字符串是:" + str);
        }

        //自己实现键盘录入数据太麻烦了,所以Java就提供了一个类供我们使用
        Scanner sc = new Scanner(System.in);

    }
}
package com.io.output;

import java.io.PrintStream;

public class SystemOutDemo02 {

    public static void main(String[] args) {

        //public static final out():标准输出流
        PrintStream ps = System.out;

        //能够方便打印各种数值
        ps.print("hello");
        ps.print(100);

        ps.println("hello");
        ps.println(100);

        //System.out的本质是一个字节输出流
        System.out.println("hello");
        System.out.println(100);

    }
}

2. 打印流

打印流分类:

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

打印流的特点:

  • 只负责输出数据,不负责读取数据
  • 有自己的特有方法

字节打印流

  • PrintStream(String fileName):使用指定的文件名创建新的打印流
  • 使用继承父类的方法写数据,查看的时候会转码,使用自己的特有方法写数据,查看的数据原样输出

示例代码:

package com.io.system;

import java.io.IOException;
import java.io.PrintStream;

public class PrintStreamDemo03 {

    public static void main(String[] args) throws IOException {

        //创建字节打印流对象
        PrintStream printStream = new PrintStream("基础语法\\src\\goods\\miku001.txt");

        //读数据
        //使用字节输出流的方法
        int len = 97;
        printStream.write(len);

        //使用特有方法写数据
        printStream.println();
        printStream.print(len);
        
        //释放资源
        printStream.close();
    }
}

字符打印流

  • PrintWriter(String fileName):使用指定的文件名创建一个新的PrintWriter,而不需要自动执行刷新
  • PrintWriter(Writer out, boolean autoFlush):创建一个新的PrintWriter
    • out :字符输出流
    • autoFlush:如果为真,则println,printf,或者format方法将刷新输出缓冲区

示例代码:

package com.io.system;

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

public class PrintWriterDemo04 {

    public static void main(String[] args) throws IOException {

        //创建字符打印流对象
        PrintWriter pw = new PrintWriter("基础语法\\src\\goods\\miku001.txt");

        pw.write("hello");
        pw.flush();
        pw.write("\n");
        pw.flush();
        pw.write("world");
        pw.flush();
        pw.write("\n");
        pw.flush();
        //字符流不能直接进文件,需要flush

        //println()和writer()方法的区别是后边会自动加一个换行符
        pw.println("hello");

        pw.close();

        //创建字符打印流对象(自动flush)
        //PrintWriter(writer out, boolean autoFlush):创建一个新的PrintWriter
        PrintWriter pw1 = new PrintWriter(new FileWriter("基础语法\\src\\goods\\miku001.txt"),true);

        pw1.println("刷新了吗");
        /* 
        pw1.write("刷新了吗");
        pw1.write("\n");
        pw1.flush();
         */
        pw1.println("刷新了");

        pw1.close();//会先刷新再关闭流

    }
}

3. 案例:复制Java文件(打印流改进版)

需求:把一个java文件复制到另一个Java文件里

package com.io.system;

import java.io.*;

public class CopyJavaDemo05 {

    public static void main(String[] args) throws IOException {

        method1();

    }

    public static void method1() throws IOException{
        //创建字符缓冲输入流对象
        BufferedReader br = new BufferedReader(new FileReader("基础语法\\src\\com\\io\\system\\CopyJavaDemo05.java"));

        //创建字符打印流对象
        PrintWriter pw = new PrintWriter(new FileWriter("基础语法\\src\\goods\\CopyTest.java"),true);

        //读数据
        String str;

        while ((str = br.readLine()) != null){

            //打印流打印
            pw.println(str);
        }

        //释放资源
        br.close();
        pw.close();
    }

    public static void method2() throws IOException {
        //创建字符缓冲输入流对象
        BufferedReader br = new BufferedReader(new FileReader("基础语法\\src\\com\\io\\system\\CopyJavaDemo05.java"));

        //创建字符缓冲输出流对象
        BufferedWriter bw = new BufferedWriter(new FileWriter("基础语法\\src\\goods\\CopyTest.java"));

        //读数据
        String str;
        int len;
        while ((str = br.readLine()) != null){

            //写一行数据
            bw.write(str);
            bw.newLine();
            bw.flush();
        }

        //释放资源
        br.close();
        bw.close();
    }
}

4. 对象序列化流

对象序列化:就是将对象保存到磁盘中,或者在网络中传输对象

这种机制就是使用一个字节序列表示一个对象,该字节序列包含:对象的类型、对象的数据和对象中存储的属性等信息字节序列写到文件之后,相当于文件中持久保存了一个对象的信息

反之,该字节序列还可以从文件中读取回来,重构对象,对它进行反序列化

要实现序列化和反序列化就要使用对象序列化流和对象反序列化流:

  • 对象序列化流:ObjectOutputStream
    • 将Java对象的原始数据和图形写入OutputStream。可以使用ObjectInputStream读取(重构)对象。可以通过使用流的文件来实现对象的持久存储。如果流是网络套接字流,则可以在另一个主机上或另一个进程中重构对象
    • 构造方法:ObjectOutputStream(OutputStream out):创建一个写入指定的OutputStream的ObjectOutputStream
    • 序列化对象的方法:void writeObject(Object obj):将指定的对象写入ObjectOutputStream
    • 一个对象想要被序列化,该对象所属的类必须实现Serializable接口
    • Serializable是一个标记接口,实现该接口,不需要重写任何方法
  • 对象反序列化流:ObjectInputStream
    • ObjectInputStream反序列化先前使用ObjectOutputStream编写的原始数据和对象
    • 构造方法:ObjectInputStream(InputStream in):创建从指定的InputStream读取的ObjectInputStream
    • 反序列化对象的方法:Object readObject():从ObjectInputStream读取一个对象

示例代码:

package com.io.object;

import java.io.*;

public class ObjectStreamDemo01 {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //对象序列化流
        //创建一个对象序列化流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("基础语法\\src\\goods\\miku001.txt"));

        //创建对象
        Student s1 = new Student("张三", 23);

        //对象序列化
        oos.writeObject(s1);//NotSerializableException

        //释放资源
        oos.close();

        //创建一个对象反序列化流对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("基础语法\\src\\goods\\miku001.txt"));

        //对象反序列化
        Object o = ois.readObject();

        //向下转型
        Student s2 = (Student)o;

        //输出
        System.out.println(s2.getName() + ", " + s2.getAge());

        //释放资源
        ois.close();

    }
}

5. 对象序列化流的问题

  1. 用对象序列化流序列化了一个对象后,假如我们修改了对象所属的类文件,读取数据会不会出问题?
  • 会出问题:抛出InvalidClassException异常
  1. 如果出问题了如何解决?
  • 给对象所属的类加一个SerialVersionUID

    private static final long ServialVersionUID = 12L;

  1. 如果一个对象中的某个成员变量不想被序列化该如何操作?
  • 给该成员变量加transient关键字修饰,该关键字标记的成员变量不参与序列化过程

示例代码:

package com.io.object;

import java.io.Serializable;

public class Student implements Serializable {//Serializable是一个标识接口
    private String name;
    private transient int age;
    private static final long serialVersionUID = 001;

    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 +
                '}';
    }
}

6. Properties

是一个集合

示例代码:

package com.io.properties;

import java.util.Properties;
import java.util.Set;

public class PropertiesDemo01 {

    public static void main(String[] args) {

        //创建Properties对象
        Properties pro = new Properties();//无泛型

        //添加元素
        pro.put("a1","张三");
        pro.put("a2","李四");
        pro.put("a3","王五");

        //遍历集合
        Set<Object> keySet = pro.keySet();
        for (Object key : keySet){
            Object o = pro.get(key);
            System.out.println(key+ " is " + o);
        }
    }
}

作为集合的特有方法

  • Object setProperty(String key, String value):设置集合的键和值,都是String类型,底层调用Hashtable put方法
  • String getProperty(String key):使用此属性列表中指定的键搜索属性
  • Set<String> stringPropertyName():从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串

示例代码

package com.io.properties;

import java.util.Properties;
import java.util.Set;

public class PropertiesDemo02 {

    public static void main(String[] args) {

        //创建集合对象
        Properties pro = new Properties();

        //特有方法 Object setProperty(String key, String value)
        pro.setProperty("a1","张三");
        pro.setProperty("a2","李四");
        pro.setProperty("a3","王五");

        System.out.println(pro);
        System.out.println("=================");

        //特有方法 String getProperty(String key)
        System.out.println(pro.getProperty("a2"));

        //特有方法 Set<String> stringPropertyNames()
        Set<String> names = pro.stringPropertyNames();

        for (String name : names){
            String value = pro.getProperty(name);
            System.out.println(name +" is " + value);
        }
    }
}

Properties和IO流结合的方法:

  • void load(InputStream inStream):从输入字节流读取属性列表(键和元素对)
  • void load(Read reader):从输入字符流读取属性列表(键和元素对)
  • void store(OutputStream out, String comments):将此属性列表(键和元素对)写入此Properties表中,以适合于使用load(InputStream)方法的格式写入输出字节流
  • void store(Writer writer, String comments):将此属性列表(键和元素对)写入此Properties表中,以适合使用load(Reader)方法的格式写入输出字符流

示例代码

package com.io.properties;

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

public class PropertiesDemo03 {

    public static void main(String[] args) throws IOException {

        //从集合中写入文件
//        myStore();

        //从文件写入集合
        myLoad();
    }

    //从文件中写入集合
    private static void myLoad() throws IOException {

        //创建Properties对象
        Properties pro = new Properties();

        //写入集合
        pro.load(new FileReader("基础语法\\src\\goods\\miku001.txt"));

        //输出
        System.out.println(pro);
        Set<String> keys = pro.stringPropertyNames();
        for (String key : keys){
            String value = pro.getProperty(key);
            System.out.println(key + ", " + value);
        }
    }

    //从集合中写入文件
    private static void myStore() throws IOException {

        //创建Properties对象
        Properties pro = new Properties();

        //添加元素
        pro.setProperty("a1","张三");
        pro.setProperty("a2","李四");
        pro.setProperty("a3","王五");

        //添加进文件
        pro.store(new FileWriter("基础语法\\src\\goods\\miku001.txt"),null);

    }
}

7. 案例:游戏次数

需求:请写程序实现猜数字小游戏,只能试玩三次,如果还想玩,提示:游戏试玩已结束,想玩请充值

package com.io.properties;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;


import static com.io.properties.Game.start;

public class PropertiesDemo04 {

    public static void main(String[] args) throws IOException {

        //创建Properties对象
        Properties prop = new Properties();

        prop.load(new FileInputStream("基础语法\\src\\goods\\game.txt"));

        String count = prop.getProperty("count");

        //将String转化为jnt
        int number = Integer.parseInt(count);

        if (number >= 3){

            System.out.println("请充值");
        } else {
            Game.start();
            number++;
            prop.setProperty("count", String.valueOf(number));
            //重新写入文件
            prop.store(new FileWriter("基础语法\\src\\goods\\game.txt"),null);
        }

        System.out.println(prop);
    }
}
posted on 2023-03-19 22:17  雪化凛然  阅读(49)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3