java_IO流

一、文件

(一)什么是文件

在这里插入图片描述

(二)文件流

在这里插入图片描述
在这里插入图片描述

输入流:本来文件有内容,显示在程序输入板
输出流:创建一个文件在电脑上

二、常用的文件操作

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

在这里插入图片描述

package com.hspedu.file;

import org.junit.Test;

import java.io.File;
import java.io.IOException;

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

    }
    //方式一 new File(String pathname)
    @Test
    public void create01() {
        String filePath = "e:\\news1.txt";
        File file = new File(filePath);
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //方式二 new File(File parent,Sting child)//根据父目录文件+子路径构建
    //e:\\new2.txt  父目录 e:\\
    @Test
    public void create02() {
        File parentFile = new File("e:\\");
        String fileName = "new2.txt";
        File file = new File(parentFile, fileName);
        //这里的file对象,在Java程序中,只是一个对象
        //只有执行了createNewFile方法,才会真正的在磁盘创建该文件
        try {
            file.createNewFile();//真正创建文件
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //方式三 new File(String parent,String child)//根据父目录+子路径构建
    @Test
    public void create03() {
        String parentPath = "e:\\";//  e:/
        String fileName = "news3.txt";
        File file = new File(parentPath, fileName);
        try {
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

(二)获取文件的相关信息

在这里插入图片描述
V在这里插入图片描述

package com.hspedu.file;

import org.junit.Test;

import java.io.File;

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


    }
    //获取文件的信息
    @Test
    public void info() {
        //先创建文件对象
        File file = new File("e:\\news1.txt");

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

(三)目录的操作和文件删除

在这里插入图片描述

package com.hspedu.file;

import org.junit.Test;

import java.io.File;

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

    }
    //判断 d:\\news1.txt 是否存在,如果存在就删除
    @Test
    public void m1() {
        String filePath = "e:\\news1.txt";
        File file = new File(filePath);
        if(file.exists()) {
            if(file.delete()) {
                System.out.println(filePath + "删除成功");
            } else {
                System.out.println("删除失败");
            }
        } else {
            System.out.println("该文件不存在");
        }
    }
    //判断D:\\demo02 是否存在,存在就删除,否则提示不存在
    //在java编程中,目录也被当做文件
    @Test
    public void m2() {
        String filePath = "D:\\demo02";
        File file = new File(filePath);
        if(file.exists()) {
            if(file.delete()) {
                System.out.println(filePath + "删除成功");
            } else {
                System.out.println("删除失败");
            }
        } else {
            System.out.println("该目录不存在");
        }
    }
    //判断 D:\\demo\\a\\b\\c 目录是否存在,如果存在就提示已经存在,否则创建
    @Test
    public void m3() {
        String directoryPath = "D:\\demo\\a\\b\\c";
        File file = new File(directoryPath);
        if(file.exists()) {
            System.out.println(directoryPath + "存在");
        } else {
            if(file.mkdirs()) { //mkdirs 创建多级目录  //mkdir 创建一级目录
                System.out.println(directoryPath + "创建成功");
            } else {
                System.out.println(directoryPath + "创建失败");
            }
        }
    }
}

三、IO流原理及流的分类

(一)java IO流原理

在这里插入图片描述
在这里插入图片描述

(二)流的分类

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
流和文件
流是文件中数据的搬运工

四、IO流体系图-常用的类

(一)InputStream:字节输入流

在这里插入图片描述
在这里插入图片描述

(二)FileInputStream 介绍

在这里插入图片描述

package com.hspedu.inputstream_;

//import com.sun.org.apache.xpath.internal.operations.String;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.IOException;

//演示FileInputStream的使用(字节输入流 文件->程序)
public class FileInputStream_ {
    public static void main(String[] args) {

    }
    //单个字节的读取,效率比较低read() -> read(byte[] b)
    @Test
    public void readFile01() {
        String filePath = "e:\\hello.txt";
        int readDate = 0;
        FileInputStream fileInputStream = null;
        try {
            //创建 FileInputStream 对象,用于读取 文件
            fileInputStream = new FileInputStream(filePath);
            //从该输入流读取一个字节的数据。 如果没有输入可用,此方法将阻止。
            //如果返回-1,表示读取完毕
            while ((readDate = fileInputStream.read()) != -1) {
                System.out.print((char)readDate);//转成char
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //使用read(byte[] b) 读取文件,提高效率
    @Test
    public void readFile02() {
        String filePath = "e:\\hello.txt";
        //字节数组
        byte[] buf = new byte[8];//一次读取8个字节
        int readLen = 0;
        FileInputStream fileInputStream = null;
        try {
            //创建 FileInputStream 对象,用于读取 文件
            fileInputStream = new FileInputStream(filePath);
            //从该输入流读取最多b.length字节的数据到字节数组。 此方法将阻塞,直到某些输入可用。
            //如果返回-1,表示读取完毕
            //如果读取正常,放回实际读取的字节数
            while ((readLen = fileInputStream.read(buf)) != -1) {
                System.out.print(new String(buf, 0, readLen));//显示
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

(三)FileOutStream 介绍

在这里插入图片描述
在这里插入图片描述

(四)FileOutputStream 应用示例1

在这里插入图片描述

package com.hspedu.outputstream_;

import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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

    }

    /**
     * 演示使用FileOutputStream 将数据写到文件中,
     * 如果该文件不存在,则创建该文件
     */
    @Test
    public void writeFile() {

        //创建FileOutputStream 对象
        String filePath = "e:\\a.txt";
        FileOutputStream fileOutputStream = null;

        try {
            //得到FileOutputStream 对象

            //1.new FileOutputStream(filePath) 创建方式,当写入内容时,会覆盖原来的内容
            //2.new FileOutputStream(filePath, true) 创建方式,当写入内容时,是追加到文件后面
            fileOutputStream = new FileOutputStream(filePath, true);
            //写入一个字节
            //fileOutputStream.write('H');

            //写入字符串
            String str = "hello,world!";
            //str.getBytes() 可以把字符串->字符数组
            //fileOutputStream.write(str.getBytes());
            //write(byte[] b, int off, int len) 将 len 字节从位于偏移量 off 的自定字节数组
            fileOutputStream.write(str.getBytes(), 0, str.length());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

(五)FileOutputStream 应用案例2

在这里插入图片描述
在这里插入图片描述

package com.hspedu.outputstream_;

import com.hspedu.file.FileInformation;

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

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

        String srcFilePath = "e:\\aa.png";
        String destFilePath = "d:\\aa.png";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            fileInputStream = new FileInputStream(srcFilePath);
            fileOutputStream = new FileOutputStream(destFilePath);
            //定义一个字节数组,提高读取效果
            byte[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = fileInputStream.read(buf)) != -1) {
                //读取到后,就写入到文件 通过 fileOutputStream
                //即,是一边读,一边写
                fileOutputStream.write(buf, 0, readLen);//一定要这个方法
            }
            System.out.println("拷贝ok");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭输入流输出流释放资源
                if(fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

(六)FileReader 和 FileWriter 介绍

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

(七)FileReader 和FileWriter 应用案例

在这里插入图片描述

package com.hspedu.reader_;

import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

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


    }
    //单个字符读取文件
    @Test
    public void readFile01() {
        String filePath = "e:\\story.txt";
        FileReader fileReader = null;
        int data = 0;
        //1.先创建FileReader对象
        try {
            fileReader = new FileReader(filePath);
            //循环读取 使用read,单个字符读取
            while ((data = fileReader.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //使用字符数组读取文件
    @Test
    public void readFile02() {
        String filePath = "e:\\story.txt";
        FileReader fileReader = null;
        int readLen = 0;
        char[] buf = new char[8];
        //1.先创建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 {
            if(fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

在这里插入图片描述

package com.hspedu.writer_;

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

public class FileWriter_ {
    public static void main(String[] args) {
        String filePath = "e:\\new2.txt";
        //创建FileWriter对象
        FileWriter fileWriter = null;
        char[] chars = {'a', 'b', 'c'};
        try {
            fileWriter = new FileWriter(filePath);//默认是覆盖写入
            //3 write(int):写入单个字符
            fileWriter.write('H');
            //4.write(char[]):写入指定数组
            fileWriter.write(chars);
            //5.write(char[], off, len):写入指定数组的指定部分
            fileWriter.write("一二三四五".toCharArray(), 0, 3);
            //6.write(string):写入整个字符串
            fileWriter.write(" 你好北京~");
            //7.write(string,off,len):写入字符串的指定部分
            fileWriter.write("上海天津", 0, 2);
            //在数据量大的情况下,可以使用循环操作

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //对应FileWriter,一定要关闭流,或者flush,才能真正把数据写入到文件
            try {
                //fileWriter.flush();
                //关闭文件流,等价flush() + 关闭
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

五、节点流和处理流

(一)基本介绍

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

(二)节点流和处理流的区别和联系

在这里插入图片描述

(三)处理流的功能主要体现以下两个方面:

在这里插入图片描述

(四)处理流_BufferedReader和BufferedWriter

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

package com.hspedu.writer_;

import java.io.BufferedReader;
import java.io.FileReader;

public class BufferedReader_ {
    public static void main(String[] args) throws Exception{
        String filePath = "e:\\story.txt";
        //创建BufferedReader
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        //读取
        String line;//按行读取,效率高
        //bufferedReader.readLine() 是按行读取文件,返回空,读取完毕
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
        //关闭流,只需要关闭bufferedReader,因为底层自动关闭节点流FileReader
        bufferedReader.close();
        /*
            public void close() throws IOException {
        synchronized (lock) {
            if (in == null)
                return;
            try {
                in.close();//in 就是我们传入的 new FileReader(filePath),关闭了
            } finally {
                in = null;
                cb = null;
            }
        }
    }
        * */
    }
}


package com.hspedu.writer_;

import java.io.BufferedWriter;
import java.io.FileWriter;

public class BufferedWriter_ {
    public static void main(String[] args) throws Exception{

        String filePath = "e:\\new3.txt";
        //创建BufferedWriter 文件
        //1.new FileWriter(filePath, true) 表示以追加的方式写入
        //2.new FileWriter(filePath) 表示以覆盖的方式写入
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath, true));
        bufferedWriter.write("hello");
        //插入一个和系统相关的换行符
        bufferedWriter.newLine();
        bufferedWriter.write("hello");
        bufferedWriter.newLine();
        bufferedWriter.write("hello");
        //插入一个换行,没有换行,横着输出


        //关闭外出流bufferedWriter
        bufferedWriter.close();
    }
}

在这里插入图片描述

package com.hspedu.writer_;

import java.io.*;

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

        //BufferedReader 和BufferedWriter 是按照字符操作
        //不要去操作二进制文件(声音,视频,doc,pdf),可能造成文件损坏
        String srcFilePath = "e:\\new3.txt";
        String destFilePath = "e:\\news3.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();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if(br != null) {
                    br.close();
                }
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

(五)处理流_BufferedInputStream和BufferedOutputStream(可以处理二进制文件)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

package com.hspedu.outputstream_;

import java.io.*;

//演示使用BufferedOutputStream 和 BufferedInputStream使用
//完成二进制拷贝
//也可以操作文本文件
public class BufferedCopy02 {
    public static void main(String[] args) {

        String srcFilePath = "e:\\aa.png";
        String destFilePath = "d:\\aa.png";

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

        try {
            //因为 FileInputStream 是 InputStream 子类
            bis = new BufferedInputStream(new FileInputStream(srcFilePath));
            bos = new BufferedOutputStream(new FileOutputStream(destFilePath));

            //循环读取文件,并写入到destFilePath
            byte[] buff = new byte[1024];
            int readLine = 0;
            //当返回-1时,文件读取完毕
            while((readLine = bis.read(buff)) != -1) {
                bos.write(buff, 0, readLine);
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭外层处理流,底层会去关闭节点流
            try {
                if(bis != null) {
                    bis.close();
                }
                if(bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

(六)对象流_ObjectInputStream和ObjectOutputStream

在这里插入图片描述
在这里插入图片描述

(七)基本介绍(处理流)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
下面用到在这里插入图片描述
在这里插入图片描述

package com.hspedu.outputstream_;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

//演示ObjectOutputStream的使用,完成数据的序列化
public class ObjectOutStream_ {
    public static void main(String[] args) throws Exception {
        //序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
        String filePath = "e:\\data.bat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));

        //存放数字,序列化数据到e:\data.bat文件中
        oos.write(100);// int -> Integer(实现了Serializable)
        oos.writeBoolean(true); //boolean -> Boolean(实现了 Serializable)
        oos.writeChar('a');//char -> Character(实现了 Serializable)
        oos.writeDouble(9.3);//double ->Double(实现了 Serializable)
        oos.writeUTF("你好");//String
        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;
    }
}

在这里插入图片描述

package com.hspedu.inputstream_;

import com.hspedu.outputstream_.Dog;

import java.io.*;

public class ObjectInputStream_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        //指定反序列化的文件
        String filePath = "e:\\data.bat";
        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());
        Object dog = ois.readObject();
        System.out.println("运行类型=" + dog.getClass());
        System.out.println("dog信息=" + dog);//底层 Object -> Dog


        //特别重要的细节
        //1.如果我们希望调用Dog的方法,需要向下转型
        //2.需要我们将Dog类的定义,拷贝到可以引用的位置
        Dog dog2 = (Dog)dog;
        System.out.println(dog2.getName());
        //关闭流, 关闭外层流,底层会关闭FileInputStream
        ois.close();
    }
}

(八)注意事项和细节说明

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

(九)标准输入输出流

在这里插入图片描述

package com.hspedu.standard;

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

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

(十)转换流_InputStreamReader和OutputStreamWriter

字节流–》字符流
在这里插入图片描述
在这里插入图片描述

出现编码:

package com.hspedu.transtormation;

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

public class CodeQuestion {
    public static void main(String[] args) throws IOException {
        //读取e:\\a.txt 文件到程序
        //1.创建一个字符输入流 BufferedReader[处理流]
        //2.使用BufferedReader 对象读取e:\\a.txt
        //3.默认情况下是按照 UTF-8 编码


        String filePath = "e:\\a.txt";
        BufferedReader br = new BufferedReader(new FileReader(filePath));

        String s = br.readLine();
        System.out.println("读取到的内容:" + s);
        br.close();
    }
}

在这里插入图片描述

这里是引用
在这里插入图片描述
在这里插入图片描述

解决编码(字节输入流):

package com.hspedu.transtormation;

import jdk.nashorn.internal.ir.CallNode;

import java.io.*;

//演示使用 InputStreamReader 转换流解决中文乱码问题
//字节流FileInputStream 转换成字符流 InputStreamReader
public class InputStreamReader_ {
    public static void main(String[] args) throws IOException {
        String filePath = "e:\\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"));

        //4.读取
        String s = br.readLine();
        System.out.println("读取内容" + s);
        //5.关闭外层流
        br.close();
    }
}

这里是引用
在这里插入图片描述

解决编码(字节输出流):

package com.hspedu.transtormation;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

//演示OutputStreamWriter 使用
// 把 FileOutputStream 字节流,转成字符流 OutputStreamWriter
//指定处理的编码 gbk/utf-8/utf8
public class OutputStreamWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:new3.txt";
        String charSet = "gbk";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
        osw.write("hi,你好");
        osw.close();
        System.out.println("按照 " + charSet + "保存文件成功");
    }
}

(十一)打印流_PrintStream 和 PrintWriter

字节输出流
在这里插入图片描述
在这里插入图片描述

字符输出流
在这里插入图片描述
在这里插入图片描述

package com.hspedu.printStream;

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

//演示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);
    }
        */
        //(1)打印方法一:out.print("john,hello");
        //因为print底层使用的是write,所以我们可以直接调用write进行打印/输出

        //(2)打印方法二:out.write("你好".getBytes());
        out.close();

        //我们可以去修改打印流输出的位置/设备
        //(3)输出修改到"e:\\f1.txt"
        //"hello" 会输出到"e:\\f1.txt"
        /*
            public static void setOut(PrintStream out) {
        checkIO();
        setOut0(out);//native 方法,修改了out
    }
        * */
        System.setOut(new PrintStream("e:\\f1.txt"));
        System.out.println("hello");
    }
}

package com.hspedu.printStream;

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

public class PrintWriter_ {
    public static void main(String[] args) throws IOException {
        //PrintWriter printWriter = new PrintWriter(System.out);
        PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));
        printWriter.print("hi,北京你好");
        printWriter.close();//flush + 关闭流,才会将数据写入到文件
    }
}

六、Properties类

(一)看一个需求

在这里插入图片描述
在这里插入图片描述

package com.hspedu.properties_;

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

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

(二)基本介绍

在这里插入图片描述
在这里插入图片描述

(三)应用案例

在这里插入图片描述

package com.hspedu.properties_;


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

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

package com.hspedu.properties_;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

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

public class Properties03 {
    public static void main(String[] args) throws IOException {
        //使用Properties类来创建配置文件,修改配置文件内容

        Properties properties = new Properties();
        //创建文件
        //1.如果该文件没有key,就是创建
        //2.如果该文件有key,就是修改
        //3.Properties 父类是 Hashtable, 底层就是Hashtable
        properties.setProperty("charset" ,"utf8");
        properties.setProperty("user","汤姆");
        properties.setProperty("pwd", "abc123");
        //将k-v 存储文件中即可
        properties.store(new FileOutputStream("src\\mysql2.properties"),null);
        System.out.println("保存文件配置成功");
    }
}

(七)本章作业

(一)1.编程题

在这里插入图片描述

package com.hspedu.homework;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Homework01 {
    public static void main(String[] args) throws IOException {
        String directoryPath = "e:\\mytemp";
        File file = new File(directoryPath);
        if(!file.exists()) {
            //创建
            if(file.mkdirs()) {
                System.out.println("创建" + directoryPath + "成功");
            } else {
                System.out.println("创建" + directoryPath + "失败");
            }
        }
        String filePath = directoryPath + "\\hello.txt";//"e:\\mytemp\\hello.txt
        file = new File(filePath);
        if(!file.exists()) {
            //创建文件
            if(file.createNewFile()) {
                System.out.println(filePath + " 创建成功");

                //如果文件存在,我们就使用BufferedWriter 字符输出流写内容
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
                bufferedWriter.write("hello,world你好");
                bufferedWriter.close();
            } else {
                System.out.println(filePath + " 创建失败");
            }
        } else {
            //如果文件存在,给出提示信息
            System.out.println(filePath + " 已经存在,不再重复创建");
        }

    }
}

(二)2.编程题

在这里插入图片描述

package com.hspedu.homework;

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

public class HomeWork02 {
    public static void main(String[] args) {
        String filePath = "e:\\story.txt";
        BufferedReader br = null;
        String line = "";
        int lineNum = 0;
        try {
            br = new BufferedReader(new FileReader(filePath));
            while ((line = br.readLine())!= null) {//循环读取
                System.out.println(++lineNum + line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

在这里插入图片描述

(三)3.编程题

在这里插入图片描述

package com.hspedu.homework;

import org.junit.Test;

import java.io.*;
import java.util.Properties;

public class Homework03 {
    public static void main(String[] args) throws IOException {
        String filePath = "src\\dog.properties";
        Properties properties = new Properties();
        properties.load(new FileReader(filePath));
        String name = properties.get("name") + "";  //Object -> String
        int age = Integer.parseInt(properties.get("age") + "");// Object -> int
        String color = properties.get("color") + "";//Object -> String

        Dog dog = new Dog(name, age, color);
        System.out.println("===dog对象信息==");
        System.out.println(dog);

        //将创建的Dog对象,序列化到文件dog.dat文件
        String serFilePath = "e:\\dog.bat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFilePath));
        oos.writeObject(dog);

        //关闭流
        oos.close();
        System.out.println("dog对象,序列化完成");

    }
    //再编写一个方法,反序列化dog
    @Test
    public void m1() throws IOException, ClassNotFoundException {
        String serFilePath = "e:\\dog.dat";
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(serFilePath));
        Dog dog = (Dog)ois.readObject();
        System.out.println("===反序列化后dog信息===");
        System.out.println(dog);
        ois.close();
    }
}
class Dog implements Serializable{
    private String name;
    private int age;
    private String color;

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

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值