Advertisement

JAVA基础知识学习笔记——I/O(二)

阅读量:

第一章 字节流

1.字节输入流的介绍

复制代码
    java.io.InputStream:字节输入流
        此抽象类是表示字节输入流的所有类的超类。
        InputStream里边定义了所有字节输入流共性的成员方法,所有的字节输入流都可以使用这些方法
    共性的成员方法:
        int read() 从输入流中读取数据的下一个字节。
        int read(byte[] b)从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。
        void close() 关闭此输入流并释放与该流关联的所有系统资源。
    java.io.FileInputStream:文件字节输入流 extends InputStream
    作用:
        把文件中的数据,以字节的方式读取到内存中
    构造方法:
        FileInputStream(File file)
        FileInputStream(String name) 
        参数:传递要读取的数据源
            String name:要读取的数据源是一个文件的路径
            File file:要读取的数据源是一个文件
        构造方法的作用:
            1.会创建FileInputStream对象
            2.会把创建好的FileInputStream对象指向要读取文件的第一个字节   
        注意:
            使用构造方法创建对象,如果要读取的文件不存在,会抛出文件找不到异常
       使用字节输入流读取文件到内存中底层原理:
        java程序==>JVM==>操作系统==>调用系统中读取文件的方法==>读取文件

2.字节输入流的基本使用:一次读取一个字节

复制代码
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    /*
    字节输入流的使用步骤(重点):
        1.创建FileInputStream对象,构造方法中绑定要读取的数据源
        2.使用FileInputStream对象中的方法read,以字节的方式读取文件
        3.释放资源
     */
    public class Demo01InputStream {
    public static void main(String[] args) throws IOException {
        //1.创建FileInputStream对象,构造方法中绑定要读取的数据源
        FileInputStream fis = new FileInputStream("day16\ a.txt");
        //2.使用FileInputStream对象中的方法read,以字节的方式读取文件
        //int read() 从文件中一次读取一个字节并返回
        /*
            我们发现读取文件是一个重复的过程,所以我们可以使用循环优化
            我们不知道文件中有多少个字节,使用while循环
            循环结束的条件,read方法读取到-1的时候结束
            
            布尔表达式((len =fis.read())!=-1)
            1.fis.read():读取文件中的一个字节
            2.len =fis.read():把读取到的字节赋值给变量len
            3.((len =fis.read())!=-1):判断变量len的值是否为-1
                len不是-1就执行循环体打印len
                len是-1结束循环
         */
        int len =0;
        while ((len =fis.read())!=-1){
            System.out.print((char)len);
        }
    
    
        /*int len = fis.read();
        System.out.println(len);//97
    
        len = fis.read();
        System.out.println(len);//98
    
        len = fis.read();
        System.out.println(len);//99
    
        len = fis.read();
        System.out.println(len);//-1*/
    
        //3.释放资源
        fis.close();
    }
    }

3.使用字节输入流一次读取多个字节

复制代码
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.Arrays;
    
    /*
    使用字节输入流一次读取多个字节
        int read(byte[] b)从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。
    明确两个内容:
        1.read方法的返回值int是什么?
            每次读取的有效字节个数
        2.read方法的参数byte[]字节数组的作用?
            起到缓冲的作用,把读取到的字节依次存储到数组中
            把数组一次性的由操作系统返回JVM,由JVM返回个java程序
            数组的长度一般定义为1024或者1024的整数倍
    String类的构造方法:
        String(byte[] bytes) 通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。
                根据编码表查询字节对应的编码,把字节转换为字符串  97-->a  65-->A
        String(byte[] bytes, int offset, int length) 把字节数组的一部分转换为字符串
               int  offset:数组中的开始索引
               int length:转换的字节个数
     */
    public class Demo02InputStream {
    public static void main(String[] args) throws IOException {
        //1.创建字节输入流FileInputStream对象,构造方法中绑定要读取的数据源
        FileInputStream fis = new FileInputStream("day16\ b.txt");
        //2.使用FileInputStream对象中的方法read,以字节的方式读取文件
        //int read(byte[] b) 使用字节数组缓冲一次读取多个字节
        /*
            我们发现读取数据,是一个重复的过程,所以可以使用循环优化
            不知道文件中有多少数据,使用while循环
            循环结束的条件,read方法返回-1的时候结束
         */
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = fis.read(bytes))!=-1){
            System.out.println(len);//5
            //把字节数组的一部分转换为字符串
            System.out.println(new String(bytes,0,len));
        }
    
    /*
     //准备文件lol.txt其中的内容是AB,对应的ASCII分别是65 66
        File f =new File("day16\ a.txt");
        //创建基于文件的输入流
        FileInputStream fis = new FileInputStream("day16\ a.txt");
        //创建字节数组,其长度就是文件的长度
        byte[] all =new byte[(int) f.length()];
        //以字节流的形式读取文件所有内容
        fis.read(all);
        for (byte b : all) {
            //打印出来是65 66
            System.out.println(b);
        }
    */
        /*byte[] bytes = new byte[2];
        int len = fis.read(bytes);
        System.out.println(len);//2
        System.out.println(Arrays.toString(bytes));//[65, 66]
        System.out.println(new String(bytes));//AB
    
        len = fis.read(bytes);
        System.out.println(len);//2
        System.out.println(new String(bytes));//CD
    
        len = fis.read(bytes);
        System.out.println(len);//1
        System.out.println(new String(bytes));//ED
    
        len = fis.read(bytes);
        System.out.println(len);//-1
        System.out.println(new String(bytes));//ED*/
    
        //3.释放资源
        fis.close();
    }
    }

4.文件复制

复制代码
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /*
    文件复制
    原理:一读一写
    数据源: c:\ 1.jpg
    目的地: d:\ 1.jpg
    实现步骤:
        1.创建FileInputStream对象,构造方法中绑定要读取的数据源
        2.创建FileOutputStream对象,构造方法中绑定要写的目的地
        3.使用FileInputStream对象中的方法read,以字节的方式读取文件
        4.使用FileOutputStream对象中的方法write,把读取到的字节写入到文件中
        5.释放资源(先关写的,后关的读的)
     */
    public class Demo01CopyFile {
    public static void main(String[] args) throws IOException {
        long s = System.currentTimeMillis();
        //1.创建FileInputStream对象,构造方法中绑定要读取的数据源
        FileInputStream fis = new FileInputStream("c:\ 1.exe");
        //2.创建FileOutputStream对象,构造方法中绑定要写的目的地
        FileOutputStream fos = new FileOutputStream("d:\ 1.exe");
        //3.使用FileInputStream对象中的方法read,以字节的方式读取文件
        //一次读取一个字节,写入一个字节的方式复制文件:效率低下
        /*int len = 0;
        while ((len = fis.read())!=-1){
            //4.使用FileOutputStream对象中的方法write,把读取到的字节写入到文件中
            fos.write(len);
        }*/
    
        //一次读取多个字节,写入多个字节的方式复制文件:效率高
        byte[] bytes = new byte[1024*1000];
        int len = 0;
        while ((len = fis.read(bytes))!=-1){
            fos.write(bytes,0,len);//写有效字节个数(最后一次读取不一定是1024个)
        }
    
        //5.释放资源(先关写的,后关的读的)
        fos.close();
        fis.close();
        long e = System.currentTimeMillis();
        System.out.println("复制文件共耗时:"+(e-s)+"毫秒!");
    }
    }

二、 字符流

1.使用字节输入流读取含有中文的文件

复制代码
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    /*
    使用字节输入流读取含有中文的文件
         文件的编码GBK:一个中文占用2个字节
         文件的编码UTF-8:一个中文占用3个字节
     */
    public class Demo01FileInputStream {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("day16\ c.txt");//c.txt 你好
        int len = 0;
        while ((len = fis.read())!=-1){
            System.out.print((char)len);//ä½ å¥½  一次读取一个字节(1/3个中文),把中文的1/3转换为字符,出现乱码
        }
        fis.close();
    }
    }

2.字符输入流介绍

复制代码
    /*
    java.io.Reader:字符输入流
        用于读取字符流的抽象类,
        是所有字符输入流的最顶层的父类,里边定义了所有字符输入流中共性的成员方法,所有的字符输入流都可以使用
    共性的成员方法:
        int read()读取单个字符。
        int read(char[] cbuf)将字符读入数组。
        void close() 关闭该流并释放与之关联的所有资源。
    java.io.FileReader:文件字符输入流 extends InputStreamReader(转换流) extends Reader
    作用:
        把文件中的数据以字符的方式读取到内存中
     构造方法:
        FileReader(File file) 
        FileReader(String fileName) 
        参数:传递要读取的数据源
           String fileName:数据源就是一个文件的路径
           File file:数据源就是一个文件                  
     */

3.使用字符输入流读取文件的步骤

复制代码
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    
    /*
    使用字符输入流读取文件的步骤(重点)
    1.创建FileReader对象,构造方法中绑定要读取的数据源
    2.使用FileReader对象中的方法read,以字符的方式读取文件
    3.释放资源
    
    String类的构造方法:
        String(char[] value) 把字符数组转换为字符串
        String(char[] value, int offset, int count) 把字符数组的一部分转换为字符串
     */
    public class Demo02Reader {
    public static void main(String[] args) throws IOException {
        //1.创建FileReader对象,构造方法中绑定要读取的数据源
        FileReader  fr = new FileReader("day16//c.txt");
        //2.使用FileReader对象中的方法read,以字符的方式读取文件
        //int read() 一次读取一个字符并返回
        /*int len = 0;
        while ((len = fr.read())!=-1){
            System.out.print((char)len);
        }*/
    
        //int read(char[] cbuf) 使用字符数组缓冲一次读取多个字符
        char[] chars = new char[1024];
        int len = 0;
        while ((len = fr.read(chars))!=-1){
            System.out.println(new String(chars,0,len));
        }
    
        //3.释放资源
        fr.close();
    }
    }

4.字符输出流介绍

复制代码
    /*
    java.io.Writer:字符输出流
        写入字符流的抽象类。
        是所有字符输出流的最顶层的父类,里边定义了所有字符输出流中共性的成员方法,所有的字符输出流都可以使用
    共性的成员方法:
        public abstract void close() :关闭此输出流并释放与此流相关联的任何系统资源。
        public abstract void flush() :刷新此输出流并强制任何缓冲的输出字符被写出。
        public void write(int c) :写出一个字符。
        public void write(char[] cbuf) :将 b.length字符从指定的字符数组写出此输出流。
        public abstract void write(char[] b, int off, int len) :从指定的字符数组写出 len字符,从偏移量 off开始输出到此输出流。
        public void write(String str) :写出一个字符串。
        public void write(String str, int off, int len) 写入字符串的某一部分。
       java.io.FileWriter:文件字符输出流  extends OutputStreamWriter(转换流) extends Writer
       作用:
        把内存中的数据,以字符的方式写入到文件中
       构造方法:
        FileWriter(File file) 
        FileWriter(String fileName) 
        参数:传递要写入的目的地
           String fileName:目的地就是一个文件的路径
           File file:目的地就是一个文件
        构造方法的作用:
            1.会创建FileWriter对象
            2.会根据构造方法中传递的文件|文件的路径,创建一个新的空白文件
            3.会把FileWriter对象,指向空白的文件                
     */

5.使用字符输出流基本步骤

复制代码
    import java.io.FileWriter;
    import java.io.IOException;
    
    /*
    字符输出流基本使用步骤(重点)
    1.创建FileWriter对象,构造方法中绑定要写入的目的地
    2.使用FileWriter对象中的方法write,把数据写入到内存缓冲区中
    3.使用FileWriter对象中的方法flush,把内存缓冲区中的数据刷新到文件中
    4.释放资源(close方法会先调用flush,把内存缓冲区中的数据刷新到文件中,再释放资源)
     */
    public class Demo01Writer {
    public static void main(String[] args) throws IOException {
        //1.创建FileWriter对象,构造方法中绑定要写入的目的地
        FileWriter fw = new FileWriter("day16\ d.txt");
        //2.使用FileWriter对象中的方法write,把数据写入到内存缓冲区中
        fw.write(100);
        //3.使用FileWriter对象中的方法flush,把内存缓冲区中的数据刷新到文件中
        //fw.flush();
        //4.释放资源(close方法会先调用flush,把内存缓冲区中的数据刷新到文件中,再释放资源)
        fw.close();
    }
    }

6.关闭和刷新的区别

复制代码
    import java.io.FileWriter;
    import java.io.IOException;
    
    /*
    关闭和刷新的区别(面试)
        flush:把内存缓冲区中的数据刷新到文件中,刷新完之后,流对象可以继续使用
        close:释放资源(释放流相关的所有系统资源和流对象),在释放之前把内存缓冲区中的数据刷新到文件中
              刷新完之后,流对象已经关闭了,就不能在使用了
       问题:
        1.程序执行完毕后e.txt中有没有内容?
        2.程序执行会不会抛出异常?
     */
    public class Demo02Writer {
    public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter("day16\ e.txt");
        fw.write(65);//A
        fw.write(66);//B
        fw.flush();//把内存缓冲区中的数据刷新到文件中,刷新完之后,流对象可以继续使用
        fw.write(67);//C
        fw.close();//把内存缓冲区中的数据刷新到文件中,刷新完之后,流对象已经关闭了,就不能在使用了
        fw.write(68);//D  IOException: Stream closed
    }
    }

7.字符输出流写数据的其他方法

复制代码
    import java.io.FileWriter;
    import java.io.IOException;
    
    /*
    字符输出流写数据的其他方法(重点)
        public void write(int c) :写出一个字符。
        public void write(char[] cbuf) :写字符数组中的多个字符
        public abstract void write(char[] b, int off, int len) :写字符数组的一部分字符;off:开始索引, len:写的字符个数
        public void write(String str) :写出一个字符串。
        public void write(String str, int off, int len) 写入字符串的某一部分。off:开始索引, len:写的字符个数
     */
    public class Demo03Writer {
    public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter("day16\ f.txt");
        //public void write(char[] cbuf) :写字符数组中的多个字符
        char[] chars = {'a','b','c','1','2','3','中','国','@','#','$'};
        fw.write(chars);//abc123中国@#$
    
        //public abstract void write(char[] b, int off, int len) :写字符数组的一部分字符;off:开始索引, len:写的字符个数
        fw.write(chars,6,2);//中国
    
        //public void write(String str) :写出一个字符串。
        fw.write("我是一个中国人,我骄傲!");
    
        //public void write(String str, int off, int len) 写入字符串的某一部分。off:开始索引, len:写的字符个数
        fw.write("我是一个中国人,我骄傲!",4,3);//中国人
    
        fw.close();
    }
    }

8.字符输出流的续写和换行

复制代码
    import java.io.FileWriter;
    import java.io.IOException;
    
    /*
    字符输出流的续写和换行(重点)
    1.续写(追加写):使用两个参数的构造方法
        FileWriter(File file, boolean append)
        FileWriter(String fileName, boolean append)
        参数:
            File file|String fileName:写入数据的目的地
            boolean append:续写开关
                true:可以续写,使用构造方法创建对象,文件名相同的,不会创建新的文件覆盖之前同名的文件
                      会继续往文件的末尾写数据
                false:不可以续写,使用构造方法创建对象,文件名相同,会创建一个新的空白的文件覆盖之前同名的文件
                      在新的文件中写数据
    2.换行:使用换行符号
        windows: \r\n
        linux: /n
        mac: /r Mac OS X开始与Linux统一
     */
    public class Demo04Writer {
    public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter("day16\ g.txt",true);
        for (int i = 1; i <=10; i++) {
            fw.write("hellworld"+i+"\r\n");
        }
        fw.flush();
        fw.close();
    }
    }

三、 IO资源的处理

1.JDK7前异常处理

复制代码
    import java.io.FileWriter;
    import java.io.IOException;
    
    /*
    JDK7前异常的处理:使用try...catch...finally处理异常
    throws:声明抛出异常对象,出现了异常,程序就停止了(JVM中断),如果有后续代码,执行不到了
    try...catch...finally:出现了异常,如果有后续代码,可以继续执行
    格式:
        try{
            可能会产生异常的代码(没有异常的代码可以放)
        }catch(定义一个异常变量,接收异常对象){
            异常的处理逻辑
        }finally{
            一定会执行的代码,一般用于资源释放(无论是否有异常,流对象都需要释放了)
        }
    快捷键:ctrl+alt+t
     */
    public class Demo01JDK7Before {
    public static void main(String[] args) {
        /*
            1.把fw.close();放在finally中:无论是否有异常,流对象都需要释放了
            Cannot resolve symbol 'fw':出了变量fw的作用域,不能使用,需要提高fw的作用域,定义在try外边
            2.Variable 'fw' might not have been initialized:变量fw没有一个初始化的值
                FileWriter fw = null; 赋一个默认值null,创建对象成功了,把对象赋值给fw;创建对象失败使用默认值null
         */
        FileWriter fw = null;
        try {
            fw = new FileWriter("w:\ g.txt",true);
            for (int i = 1; i <=10; i++) {
                fw.write("hellworld"+i+"\r\n");
            }
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.增加一个非空判断,防止空指针异常,流对象的值是null,就不需要关闭了
            if(fw!=null){
                try {
                    //3.fw.close方法本身会声明抛出异常,需要try...catch
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        System.out.println("后续代码!");
        System.out.println(1);
        System.out.println(2);
        System.out.println(3);
    }
    }

2.JDK7后异常处理

复制代码
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.util.ArrayList;
    import java.util.concurrent.Executors;
    
    /*
    JDK7后异常处理:使用try...catch处理异常
    格式:
        try(
            //定义流对象,只能定义流对象
            AAA aaa = new AAA(读);
            BBB bbb = new BBB(写);
        ){
            可能产生异常的代码
            aaa.read();
            bbb.write():
        }catch(定义一个异常相关的变量,接收异常对象){
            异常的处理逻辑
        }
    注意:
        在try的后边增加一个(),在()中定义流对象
        那么这些流对象的作用域,就在try中有效,执行完try中的代码,会自动帮助我们释放流对象的
        省略finally
     */
    public class Demo02JDK7After {
    public static void main(String[] args) {
        try(
            //定义流对象
            FileWriter fw = new FileWriter("day16\ 1.txt");
        ){
            fw.write("哈哈,你猜我能写入到文件中吗?");
        }catch (Exception e){
            e.printStackTrace();
        }
    
        try(
            //定义流对象
            FileInputStream fis = new FileInputStream("c:\ 2.jpg");
            FileOutputStream fos = new FileOutputStream("d:\ 2.jpg");
        ){
            byte[] bytes = new byte[1024*1000];
            int len = 0;
            while ((len = fis.read(bytes))!=-1){
                fos.write(bytes,0,len);//写有效字节个数(最后一次读取不一定是1024个)
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    }

四、 Properties集合

1.Properties集合的基本使用

复制代码
    import java.util.Properties;
    import java.util.Set;
    
    /*
    java.util.Properties集合 extends Hashtable<k,v>双列集合
    1.Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。
        Properties集合是一个唯一和IO流相结合的集合
        我们可以使用Properties集合中的方法store,把集合中的临时数据,持久化存储到硬盘中(内存-->硬盘)
        我们可以使用Properties集合中的方法load,把硬盘中保存的键值对文件,读取到内存集合中使用(硬盘-->内存)
    2.属性列表中每个键及其对应值都是一个字符串。
        Properties集合是一个双列集合,可以不用写泛型,默认key和value都是String类型
     */
    public class Demo01Properties {
    public static void main(String[] args) {
        show01();
    }
    
    /*
        Properties集合的基本使用:使用Properties集合存储数据,遍历集合获取集合中元素
        Properties集合健和值默认都是String类型,集合中有一些和String相关的方法
            Object setProperty(String key, String value) 往Properties集合中添加键值对,相当于Map集合中的put方法
            String getProperty(String key) 根据key获取vlaue,相当于Map集合中的get(key)方法
            Set<String> stringPropertyNames() 返回此属性列表中的键集,相当于Map集合中的keySet方法
     */
    private static void show01() {
        //创建Properties集合对象
        Properties prop = new Properties();
        //使用Properties集合中的方法setProperty往集合中添加键值对
        prop.setProperty("迪丽热巴","168");
        prop.setProperty("古力娜扎","165");
        prop.setProperty("赵丽颖","160");
        prop.setProperty("唐嫣","170");
        //使用Properties集合中的方法stringPropertyNames,获取集合中所有的key,把Key存储到一个Set集合中返回
        Set<String> set = prop.stringPropertyNames();
        //遍历Set集合,获取Properties集合中的每一个key
        for (String key : set) {
            //使用Properties集合中的方法getProperty根据key获取value值
            String value = prop.getProperty(key);
            System.out.println(key+"="+value);
        }
    }
    }

2.Properties集合中的方法store

复制代码
    /*
    我们可以使用Properties集合中的方法store,把集合中的临时数据,持久化存储到硬盘中(内存-->硬盘)
    void store(OutputStream out, String comments)
    void store(Writer writer, String comments)
    方法的参数:
        OutputStream out:传递字节输出流,不能写中文,会出现乱码,可以传递OutputStream任意的子类对象
        Writer writer:传递字符输出流,能写中文,不会出现乱码,可以传递Writer任意的子类对象
        String comments:注释,解释说明我们保存的文件是什么用的,一般传递""
            注释不能写中文,默认使用Unicode编码,会出现乱码
    使用步骤:
        1.创建Properties集合对象,往集合中添加数据
        2.使用Properties集合中的方法store,把集合中的临时数据,持久化存储到硬盘中
     */
    private static void show02() throws IOException {
    //1.创建Properties集合对象,往集合中添加数据
    Properties prop = new Properties();
    prop.setProperty("迪丽热巴","168");
    prop.setProperty("古力娜扎","165");
    prop.setProperty("赵丽颖","160");
    prop.setProperty("唐嫣","170");
    
    //2.使用Properties集合中的方法store,把集合中的临时数据,持久化存储到硬盘中
    //FileOutputStream fos = new FileOutputStream("day16\ prop1.txt");
    //prop.store(fos,"save data");
    //fos.close();
    
    //如果对象只使用一次,可以使用匿名对象
    prop.store(new FileOutputStream("day16\ prop1.txt"),"save data");
    prop.store(new FileWriter("day16\ prop2.txt"),"save data");
    //一般使用存储键值对的文件,叫配置文件,结尾一般都使用.properties
    prop.store(new FileWriter("day16\ prop.properties"),"save data");
    }

3.Properties集合中的方法load

复制代码
    /*
    我们可以使用Properties集合中的方法load,把硬盘中保存的键值对文件,读取到内存集合中使用(硬盘-->内存)
    void load(InputStream inStream) 传递字节输入流,不能读取含有中文的文件,可以传递InputStream任意的子类对象
    void load(Reader reader)  传递字符输入流,可以读取含有中文的文件,可以传递Reader任意的子类对象
    使用步骤:
        1.创建Properties集合对象
        2.使用Properties集合中的方法load,把硬盘中保存的键值对文件,读取到内存集合中使用
        3.遍历Properties集合
    注意:
        1.在Properties集合的配置文件中,可以使用#进行注释,被注释的键值对不会被读取
        2.在Properties集合的配置文件中,健和值之间可以使用=,空格,冒号等一些符号作为键与值的分割符号
        3.在Properties集合的配置文件中,健和值默认都是字符串类型,不需要添加引号,否则会画蛇添足
     */
    private static void show03() throws IOException {
    //1.创建Properties集合对象
    Properties prop = new Properties();
    //2.使用Properties集合中的方法load,把硬盘中保存的键值对文件,读取到内存集合中使用
    //prop.load(new FileInputStream("day16\ prop.properties"));
    prop.load(new FileReader("day16\ prop.properties"));
    //3.遍历Properties集合
    Set<String> set = prop.stringPropertyNames();
    for (String key : set) {
        String value = prop.getProperty(key);
        System.out.println(key+"\t"+value);
    }
    }

五、 ResourceBundle工具类

1.ResourceBundle类对象的创建

复制代码
    mport java.util.ResourceBundle;
    
    /*
    java.util.ResourceBundle:操作资源的工具类
    作用:
        我们可以使用ResourceBundle类中的方法读取以.properties结尾的文件
    ResourceBundle是一个抽象类,无法直接创建对象使用,我们可以使用ResourceBundle类中的静态方法获取ResourceBundle的子类对象
        static ResourceBundle getBundle(String baseName)
        参数:
           String baseName:传递以.properties结尾的文件名称
            prop.properties==>prop
            data.properties==>data
        注意:
             .properties结尾的文件必须放在当前模块的src下边,否则获取对象找不到配置文件,会抛出异常
     */
    public class Demo01ResourceBundle {
    public static void main(String[] args) {
        //多态 父类           =  子类对象
        ResourceBundle bundle = ResourceBundle.getBundle("data");
        System.out.println(bundle);//java.util.PropertyResourceBundle@74a14482
    }
    }

2.ResourceBundle类的getString方法

复制代码
    import java.util.ResourceBundle;
    
    /*
    ResourceBundle类中提供了一个方法叫getString,用于读取配置文件
        String getString(String key)  根据配置文件中key,读取配置文件中的value
    注意:
        配置文件中key和value不要使用中文    
     */
    public class Demo02ResourceBundle {
    public static void main(String[] args) {
        //获取ResourceBundle对象
        ResourceBundle bundle = ResourceBundle.getBundle("data");
        //使用ResourceBundle对象中的方法getString,根据配置文件中key,读取配置文件中的value
        String username = bundle.getString("username");
        System.out.println(username);//jack
        String password = bundle.getString("password");
        System.out.println(password);//1234
        String sex = bundle.getString("sex");
        System.out.println(sex);//sex=女 Å®
        //String age = bundle.getString("年龄");//MissingResourceException: Can't find resource for bundle java.util.PropertyResourceBundle, key 年龄
        //System.out.println(age);
    }
    }

全部评论 (0)

还没有任何评论哟~