【Java基础】IO流

IO流

文件

什么是文件

文件是保存数据的地方,如:Word文档、TXT文件等,既可以保存图片,也可以保存视频、声音

文件流

文件在程序中是以流的形式来操作的

Java45

常用的文件操作

创建文件对象相关构造器和方法

FileCreate:

public class FileCreate {
    public static void main(String[] args) {

    }

    // 方式一
    // new File(String pathname)
    @Test
    public void create1() { // 根据路径构建一个File对象
        String filePath = "d:\\news2.txt";
        File file = new File(filePath);

        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //  方式二
    // new File(File parent, String child) // 根据父目录文件+子路径构建
    // d:\\news2.txt
    @Test
    public void create2() {
        File parentFile = new File("d:\\");
        String fileName = "news2.txt";
        // 这里的file对象,在java程序中,只是一个对象
        // 只有执行了 createNewFile(),才会真正的在磁盘中创建该文件
        File file = new File(parentFile, fileName);

        try {
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 方式三
    // new File(String parent, String child) // 根据父目录+子路径构建
    @Test
    public void create3() {
//        String parentPath = "d:/";
        String parentPath = "d:\\";
        String fileName = "news3.txt";
        File file = new File(parentPath, fileName);

        try {
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

获取文件的相关信息

FileInformation:

public class FileInformation {
    public static void main(String[] args) {

    }

    // 获取文件信息
    @Test
    public void info() {
        // 先创建文件对象
        File file = new File("d:\\news1.txt");
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 调用相应的方法,得到对应信息
        System.out.println("文件名字= " + file.getName());
        System.out.println("文件的绝对路径= " + file.getAbsolutePath());
        System.out.println("文件父级目录= " + file.getParent());
        System.out.println("文件的大小(字节)= " + file.length()); // UTF-8 英文:2byte 汉字:3byte
        System.out.println("文件是否存在= " + file.exists()); // T
        System.out.println("是不是一个文件= " + file.isFile()); // T
        System.out.println("是不是一个目录= " + file.isDirectory()); // F
    }
}

目录的操作和文件删除

Directory_:

public class Directory_ {
    public static void main(String[] args) {

    }

    // 判断 d:\\news1.txt 是否存在,如果存在就删除
    @Test
    public void m1() {
        String filePath = "d:\\news1.txt";
        File file = new File(filePath);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println(filePath + "删除成功");
            } else {
                System.out.println(filePath + "删除失败");
            }
        } else {
            System.out.println("该文件不存在");
        }
    }

    // 判断 d:\\111 是否存在,如果存在就删除,否则提示不存在
    // 在java中,目录也被当成文件
    @Test
    public void m2() {
        String filePath = "d:\\111";
        File file = new File(filePath);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println(filePath + "删除成功");
            } else {
                System.out.println(filePath + "删除失败");
            }
        } else {
            System.out.println("该目录不存在");
        }
    }

    // 判断 d:\111\a\b\c 目录是否存在,如果存在就提示已经存在,否则就创建
    @Test
    public void m3() {
        String directoryPath = "d:\\111\\a\\b\\c";
        File file = new File(directoryPath);
        if (file.exists()) {
                System.out.println(directoryPath + "存在..");
            } else {
                if (file.mkdirs()) {
                    // 创建一级目录使用mkdir()
                    // 创建多级目录使用mkdirs()
                    System.out.println(directoryPath + "创建成功..");
                } else {
                    System.out.println(directoryPath + "创建失败..");
                }
            }
    }
}

IO流原理及流的分类

Java IO流原理

1.I/O是Input/Output的缩写,I/O技术是非常实用的技术,用于处理数据传输,如:读/写文件、网络通讯等

2.Java程序中,对于数据的输入/输出操作以“流(stream)”的方式进行

3.java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过方法输入或输出数据

4.输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中

5.输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中

流的分类

1.按操作数据单位不同分为:字节流(8bit)二进制文件,字符流(按字符)文本文件

2.按数据流的流向不同分为:输入流,输出流

3.按流的角色不同分为:节点流,处理流/包装流

Java46

1)Java的IO流共涉及40多个类,都是从以上4个抽象基类派生的

2)由这4个类派生出来的子类名称都是以其父类名作为子类名后缀

IO流体系图-常用的类

Java47

InputStream:字节输入流

InputStream抽象类是所有类字节输入流的超类

InputStream常用的子类

1.FileInputStream:文件输入流

2.BufferedInputStream:缓冲字节输入流

3.ObjectInputStream:对象字节输入流

FileInputStream

演示 FileInputStream 的使用(字节输入流 文件 -> 程序)

FileInputStream_:

public class FileInputStream_ {
    public static void main(String[] args) {

    }

    // 演示读取文件..
    // 单个字节的读取,效率比较低
    @Test
    public void readFile01() {
        String filePath = "d:\\hello.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            // 创建 FileInputStream 对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);

            // 从该输入流读取一个字节的数据,如果没有输入可以使用,此方法将阻止
            // 如果返回 -1,表示读取完毕
            while ((readData = fileInputStream.read()) != -1) {
                System.out.print((char)readData); // 转成char显示
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 使用 read(byte[] b) 读取文件,提高效率
    @Test
    public void readFile02() {
        String filePath = "d:\\hello.txt";
        // 字节数组
        byte[] buf = new byte[8]; // 一次读取8个字节

        int readLen = 0;
        FileInputStream fileInputStream = null;
        try {
            // 创建 FileInputStream 对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);

            // 从该输入流读取最多buf.length字节的数据到字节数组(这里最多为8字节),
            // 此方法将阻塞,直到某些输入可用
            // 如果返回 -1,表示读取完毕
            // 如果读取正常,返回实际读取的字节数
            while ((readLen = fileInputStream.read(buf)) != -1) {
                System.out.print(new String(buf,0,readLen)); // 转成字符串显示
                /**
                * Params:
                * buf – the buffer into which the data is read.
                * offset – the start offset in the destination array buf
                * readLen – the maximum number of bytes read.
                */
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

FileOutputStream

演示使用 FileOutputStream 将数据写到文件中

FileOutputStream01:

public class FileOutputStream01 {
    public static void main(String[] args) {

    }

    // 如果该文件不存在,则创建该文件
    @Test
    public void writeFile() {
        // 创建 FileOutPutStream对象
        String filePath = "d:\\a.txt";
        FileOutputStream fileOutputStream = null;

        try {
            // 得到 fileOutputStream 对象
            fileOutputStream = new FileOutputStream(filePath,true);

            // new FileOutputStream(filePath);
            // 写入内容会覆盖原来的内容

            //new FileOutputStream(filePath, true);
            // 写入内容会追加到文件后面
            
            // 1. 写入一个字节
//            fileOutputStream.write('H');

            // 2. 写入字符串
            String str = "hello,pioneer!";
            // str.getBytes() 可以把 字符串 -> 字节数组
//            fileOutputStream.write(str.getBytes());

            // 3.
            fileOutputStream.write(str.getBytes(),0, 3);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

文件拷贝

FileCopy:

public class FileCopy {
    public static void main(String[] args) {
        // 完成文件拷贝,将e:\\Android.jpg 拷贝到 d:\\
        // 1. 创建文件的输入流,将文件读入到程序
        // 2. 创建文件的输出流,将程序读取到的文件数据,写入到指定文件

        String srcFilePath = "e:\\Android.jpg";
        String destFilePath = "d:\\Android.jpg";

        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            fileInputStream = new FileInputStream(srcFilePath);
            fileOutputStream = new FileOutputStream(destFilePath);

            int readLen = 0;

            // 定义一个字节数组,提高读取效率
            byte[] buf = new byte[1024];
            while ((readLen = fileInputStream.read(buf)) != -1) {
                // 读取到后,就写到文件
                // 即,一边读一边写
                // fileOutputStream.write(buf); // 一次可能读不够,导致数据显示不完整
                fileOutputStream.write(buf, 0, readLen);
            }
            System.out.println("拷贝成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 判断 输入/输出流为空的话相当于对象都没有创建成功,
                // 就会发生空指针异常
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}

FileReader

FileReader_:

public class FileReader_ {
    public static void main(String[] args) {

    }

    /**
    * 单个字符读取文件
    */
    @Test
    public void readFile01() {
        // 读取 d:\\b.txt 文件的数据并显示
        String filePath = "d:\\b.txt";
        FileReader fileReader = null;
        int data = 0;
        // 创建FileReader对象
        try {
            fileReader = new FileReader(filePath);
            while ((data = fileReader.read()) != -1) {
                System.out.print((char)data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
    *
    */
    @Test
    public void readFile02() {
        // 读取 d://b.txt 文件的数据并显示
        String filePath = "d:\\b.txt";
        FileReader fileReader = null;

        int readLen = 0;
        char[] buf = new char[8];
        // 创建FileReader对象
        try {
            fileReader = new FileReader(filePath);
            // 循环读取,使用read(buf),返回的是实际读取到的字符数
            // 如果返回-1,说明到文件结束
            while ((readLen = fileReader.read(buf)) != -1) {
                System.out.print(new String(buf,0,readLen)); // 将字符转为字符串
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

FileWriter

FileWriter_:

public class FileWriter_ {
    public static void main(String[] args) {
        // 在 d:\\c.txt 中写入数据
        // 创建 FileWriter对象
        FileWriter fileWriter = null;
        String filePath = "d:\\c.txt";
        char[] chars = {'a', 'b' , 'c'};

        try {
            fileWriter = new FileWriter(filePath); // 默认覆盖原来的数据
            // write(int):写入单个字符
            fileWriter.write('H');

            // write(char[]):写入指定数组
            fileWriter.write(chars);

            // write(char[], off, len):写入指定数组的指定部分
            fileWriter.write("哈哈哈哈".toCharArray(),0,3);

            // write(string):写入整个字符串
            fileWriter.write("你好!Aa");

            // write(string, off, len):写入字符串的指定部分
            fileWriter.write("上海天津",0,2); // 上海
            // 在数据量大的情况下,可以使用循环操作
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 对于 FileWriter,一定要 关闭流/flush
            // 才能真正的写入数据
            /**
            *  源码:
            *  private void writeBytes() throws IOException {
            *         this.bb.flip();
            *         int var1 = this.bb.limit();
            *         int var2 = this.bb.position();
            *
            *         assert var2 <= var1;
            *
            *         int var3 = var2 <= var1 ? var1 - var2 : 0;
            *         if (var3 > 0) {
            *             if (this.ch != null) {
            *                 assert this.ch.write(this.bb) == var3 : var3;
            *             } else {
            *                 this.out.write(this.bb.array(), this.bb.arrayOffset() + var2, var3);
            *             }
            *         }
            *
            *         this.bb.clear();
            *     }
            */

            if (fileWriter != null) {
                try {
                    // fileWriter.flush();
                    // 关闭文件流,等价于 flush() + 关闭
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

flush和close区别

简单来说,close包含flush功能,但是flush具备刷新完,还可以继续写操作,
close执行完了就流关闭了,不能再写入,所以,不能用close来代替flush

节点流和处理流

基本介绍

数据源:就是存放数据的地方

Java48

节点流和处理流一览图

Java49

节点流和处理流的区别和联系

1.节点流是底层流/低级流,直接跟数据源相接

2.处理流(包装流)包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出

3.处理流(也叫包装流)对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连

处理流的功能主要体现在以下两个方面

1.性能的提高:主要以增加缓冲的方式来提高输入输出的效率

2.操作的便捷:处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加方便灵活

处理流-BufferedReader和BufferedWriter

BufferedReader和BufferedWriter属于字符流,是按照字符来读取数据的,
关闭处理时,只需要关闭外层流即可

BufferedReader_:

public class BufferedReader_ {
    public static void main(String[] args) throws Exception {
        String filePath = "d:\\b.txt";
        // 创建bufferedReader
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        // 读取
        String line; // 按行读取,效率高

        // 1. bufferedReader.readLine() 是按行读取文件
        // 2. 当返回null时,表示文件读取完毕
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }

        // 关闭流,只需要关闭 BufferedReader,因为底层会自动关闭节点流
        // FileReader

        /* 源码:
            public void close() throws IOException {
                    synchronized (lock) {
                    // private Reader in; 这里的in指传入的FileReader
                        if (in == null)
                            return;
                        try {
                            in.close();
                        } finally {
                            in = null;
                            cb = null;
                        }
                    }
                }
        */
        bufferedReader.close();
    }
}

BufferedWriter:

public class BufferedWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\ok.txt";

        // 创建 BufferedWriter
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath,true));

        bufferedWriter.write("Hello,你好啊!");
        // 插入一个和系统相关的换行
        bufferedWriter.newLine();
        bufferedWriter.write("Hello,你好啊!");


        // 关闭外层流即可,传入的new FileWriter(filePath),会在底层关闭
        bufferedWriter.close();
    }
}

BufferedCopy_:

public class BufferedCopy_ {
    public static void main(String[] args) {

        // 注意:
        // 1. BufferedReader 和 BufferedWriter 是按照字符操作
        // 2. 不要去操作二进制文件(声音、视频、doc、PDF等等),可能造成文件损坏

        String srcFilePath = "d:\\ok.txt";
        String destFilePath = "d:\\ok2.txt";

        BufferedReader br = null;
        BufferedWriter bw = null;

        String line;
        try {
            br = new BufferedReader(new FileReader(srcFilePath));
            bw = new BufferedWriter(new FileWriter(destFilePath));

            // readLine 读取一行的内容,但是没有换行
            while ((line = br.readLine()) != null) {
                // 每读取一行,就写入
                bw.write(line);
                // 插入一个换行
                bw.newLine();
            }
            System.out.println("拷贝完毕!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                if (br != null) {
                    br.close();
                }
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

处理流-BufferedInputStream和BufferedOutputStream

BufferedCopy02:

/**
* @author Pioneer
* version 1.0
* 演示使用 BufferedOutputStream 和 BufferedInputStream
* 使用它们,可以完成二进制文件拷贝(文本文件也可以,可能出现乱码)
*/
public class BufferedCopy02 {
    public static void main(String[] args) {

        String srcFilePath = "d:\\qq.jpg";
        String destFilePath = "d:\\qq2.jpg";

        // 创建 BufferedOutputStream 和 BufferedInputStream
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            bis = new BufferedInputStream(new FileInputStream(srcFilePath));
            bos = new BufferedOutputStream(new FileOutputStream(destFilePath));

            // 循环读取文件,并写入 destFilePath
            byte[] buf = new byte[1024];
            int readLine = 0;
            while ((readLine = bis.read(buf)) != -1) {
                bos.write(buf,0, readLine);
            }
            System.out.println("文件拷贝完毕!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭外层流即可
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

对象流-ObjectInputStream和ObjectOutputStream

序列化和反序列化

1.序列化就是在保存数据时,保存数据的值和数据类型

2.反序列化就是在恢复数据时,恢复数据的值和数据类型

3.需要让某个对象支持序列化机制,则必须让其类是可序列化的,该类必须实现如下两个接口之一:

Serializable // 这是一个标记接口,没有方法(推荐使用)

Externalizable // 该接口有方法需要实现

基本介绍

1.功能:提供了对基本类型或对象类型的序列化和反序列化的方法

2.ObjectOutputStream提供序列化功能

3.ObjectInputStream提供反序列化功能

Java50

ObjectOutputStream_:

public class ObjectOutputStream_ {
    public static void main(String[] args) throws Exception {
        // 序列化后,保存的文件格式,不是存文本,而是按照其格式来保持
        String filePath = "d:\\data11.dat";

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));

        // 序列化数据到 d:\\data11.dat
        oos.writeInt(100); // int -> Integer (实现了 Serializable)
        oos.writeBoolean(true); // boolean -> Boolean(实现了 Serializable)
        oos.writeChar('a'); // char -> Character(实现了 Serializable)
        oos.writeDouble(1.1); // double -> Double(实现了 Serializable)
        oos.writeUTF("你好"); // String
        // 保存一个dog对象
        oos.writeObject(new Dog("旺财",10));

        oos.close();
        System.out.println("数据保存完毕(序列化形式)");
    }
}

// 如果需要序列化某个类的对象,实现 Serializable
class Dog implements Serializable {
    private String name;
    private int age;

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

ObjectInputStream_:

public class ObjectInputStream_ {
    public static void main(String[] args) throws Exception {
        // 指定反序列化文件
        String filePath = "d:\\data11.dat";

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));

        // 1. 读取(反序列化)的顺序需要和保存数据(序列化)的顺序一致
        // 2. 否则会出现异常
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readChar());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());

        // dog 的编译类型 Object
        Object dog = ois.readObject();
        System.out.println("运行类型=" + dog.getClass()); // Dog
        System.out.println("dog信息=" + dog); // 底层 Object -> Dog

        // 注意:
        // 1. 如果希望调用Dog的方法,需要向下转型
        // 2. 需要将Dog类的定义,放到可以引用的位置
        Dog dog2 = (Dog) dog;
        System.out.println(dog2.getAge());
        // 关闭外层流即可,底层会自动关闭 FileInputStream
        ois.close();
    }
}

注意事项和细节说明

1.读写顺序要一致

2.要求序列化或反序列化对象,需要实现Serializable

3.序列化的类中建议添加SerialVersionUID,为了提高版本的兼容性

4.序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员

5.序列化对象时,要求里面属性的类型也需要实现序列化接口

6.序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现了序列化

code:

// 序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员
private static String nation;
private transient String color;

// 序列化的类中建议添加SerialVersionUID,为了提高版本的兼容性
// (不代表是新的类,只是该类的升级)
// 简单来说,Java的序列化机制是通过在运行时判断类的serialVersionUID来验证版本一致性的
private static final long serialVersionUID = 1L;

标准输入输出流

介绍

System.in 标准输入

System.out 标准输出

InputAndOutput:

public class InputAndOutput {
    public static void main(String[] args) {
        // public final static InputStream in = null;
        // System.in 编译类型 InputStream
        // System.in 运行类型 BufferedInputStream
        // 表示标准输入 键盘
        System.out.println(System.in.getClass());

        // public final static PrintStream out = null;
        // System.out 编译类型 PrintSteam
        // System.out 运行类型 PrintStream
        // 表示标准输出 显示器
        System.out.println(System.out.getClass());
    }
}

转换流-InputStreamReader和OutputStreamWriter

演示使用 InputStreamReader 转换流解决中文乱码问题

/**
* @author Pioneer
* version 1.0
* 演示使用 InputStreamReader 转换流解决中文乱码问题
* 将字节流 FileInputStream 转成字符流 InputStreamReader,指定编码 gbk/utf-8
**/
public class InputStreamReader_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\a.txt";
        // 1. 把 FileInputStream 转成 InputStreamReader
        // 2. 指定编码 gbk
//        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath),"gbk");
        // 3. 把 InputStreamReader 传入 BufferedReader
//        BufferedReader br = new BufferedReader(isr);

        // 将 2 和 3 合在一起
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"gbk"));

        String s = br.readLine();
        System.out.println(s);
        br.close();
    }
}

演示 OutputStreamWriter 使用

/**
* @author Pioneer
* version 1.0
* 演示 OutputStreamWriter 使用
* 把 FileOutputStream 字节流 转成 OutputStreamWriter
* 指定处理的编码 gbk/utf-8
*/
public class OutputStreamWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\e.txt";
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), "utf-8"));
        bw.write("大家好!111A");
        bw.close();
    }
}

打印流-PrintSteam和PrintWriter

打印流只有输出流,没有输入流

演示 PrintStream(字节打印流/输出流)

/**
* @author Pioneer
* version 1.0
* 演示 PrintStream(字节打印流/输出流)
*/
public class PrintStream_ {
    public static void main(String[] args) throws IOException {
        PrintStream out = System.out;
        // 在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
        /*
            public void print(String s) {
                if (s == null) {
                    s = "null";
                }
                write(s);
            }
        */
        out.print("hello");
        // print底层使用的是write,所以可以直接调用write进行打印/输出
        out.write("你好,DDD".getBytes());
        out.close();

        // 可以修改打印流输出的 位置/设备
        // 修改成到 d:\\f1.txt
        System.setOut(new PrintStream("d:\\f1.txt"));
        System.out.println("I am find,我很好!");
    }
}

演示 PrintWriter 使用方式

/**
* @author Pioneer
* version 1.0
* 演示 PrintWriter 使用方式
*/
public class PrintWriter_ {
    public static void main(String[] args) throws IOException {
//        PrintWriter printWriter = new PrintWriter(System.out);
        PrintWriter printWriter = new PrintWriter(new FileWriter("d:\\f2.txt"));
        printWriter.write("hi,北京你好!");
        printWriter.close();
    }
}

Properties类

传统方法

mysql.properties:

ip=192.168.100.101
user=root
pwd=12345

Properties01:

public class Properties01 {
    public static void main(String[] args) throws IOException {
        // 读取 mysql.properties 文件,并得到 ip,user,pwd
        BufferedReader br = new BufferedReader(new FileReader("src/main/java/properties_/mysql.properties"));
        String line = "";
        while((line = br.readLine()) != null) { // 循环读取
            String[] split = line.split("=");
            System.out.println(split[0] + " 值是:" + split[1]);
        }

        br.close();
    }
}

基本介绍

1.专门用于读写配置文件的集合类

配置文件的格式:

键=值
键=值

2.注意:键值对不需要有空格,值不需要用引号引起来,默认类型是String

3.Properties的常见方法

load:加载配置文件的键值对到Properties对象

list:将数据显示到指定设备

getProperties(key):根据键获取值

setProperties(key,value):设置键值对到Properties对象

store:将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,
如果有中文,会存储为Unicode码

Properties02:

public class Properties02 {
    public static void main(String[] args) throws IOException {
        // 使用 Properties 类来读取mysql.properties文件
        // 1. 创建 Properties对象
        Properties properties = new Properties();
        // 2. 加载指定配置文件
        properties.load(new FileReader("src/main/java/properties_/mysql.properties"));
        // 3. 把k-v显示到控制台
        properties.list(System.out);
        // 4. 根据key获取对应的值
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        System.out.println("用户名=" + user);
        System.out.println("密码=" + pwd);
    }
}

Properties03:

public class Properties03 {
    public static void main(String[] args) throws IOException {
        // 使用 Properties类 来创建配置文件,修改配置文件内容
        Properties properties = new Properties();
        // 创建
        // 1. 如果该文件没有key,就是创建
        // 2. 如果该文件存在key,就是修改
        /*
            Properties的 父类是 HashTable,底层就是 HashTable 核心方法:
                public synchronized V put(K key, V value) {
                // Make sure the value is not null
                if (value == null) {
                    throw new NullPointerException();
                }

                // Makes sure the key is not already in the hashtable.
                Entry<?,?> tab[] = table;
                int hash = key.hashCode();
                int index = (hash & 0x7FFFFFFF) % tab.length;
                @SuppressWarnings("unchecked")
                Entry<K,V> entry = (Entry<K,V>)tab[index];
                for(; entry != null ; entry = entry.next) {
                    if ((entry.hash == hash) && entry.key.equals(key)) {
                        V old = entry.value;
                        entry.value = value; // 如果key存在,就替换值
                        return old;
                    }
                }

                addEntry(hash, key, value, index); // 如果是新key,就addEntry
                return null;
            }
        */
        properties.setProperty("charset","utf8");
        properties.setProperty("user","汤姆"); // 保存时,是中文的Unicode码值
        properties.setProperty("pwd","8888888");

        // 将k-v 存储在文件中即可
        // comments: 指的是可以添加配置文件的注释信息
        properties.store(new FileOutputStream("src/main/java/properties_/mysql2.properties"),"hello");
        System.out.println("保存配置文件成功!");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值