IO流(师从韩顺平)

news2025/2/28 14:22:58

文章目录

  • 文件
    • 什么是文件
    • 文件流
  • 常用的文件操作
    • 创建文件对象相关构造器和方法
      • 应用案例
    • 获取文件的相关信息
      • 应用案例
    • 目录的操作和文件删除
      • 应用案例
  • IO 流原理及流的分类
    • Java IO 流原理
    • IO流的分类
  • IO 流体系图-常用的类
    • IO 流体系图(重要!!!!!)
    • 文件 VS IO流
  • FileInputStream 介绍
    • 简单案例
  • FileOutputStream 介绍
    • 应用实例
  • 文件拷贝
  • 字符流
    • FileReader 和 FileWriter 介绍
    • FileReader 相关方法
    • FileWriter 常用方法
    • 应用案例
  • 节点流和处理流
    • 基本介绍
    • 节点流和处理流一览图
    • 节点流和处理流的区别和联系
    • 处理流的功能主要体现在以下两个方面
    • 处理流-BufferedReader 和 BufferedWriter
    • 处理流-BufferedInputStream 和 BufferedOutputStream
    • 对象流-ObjectInputStream 和 ObjectOutputStream
      • 对象流介绍
      • 对象处理流使用细节
    • 标准输入输出流
    • 转换流-InputStreamReader 和 OutputStreamWriter(解决中文乱码)
    • 打印流-PrintStream 和 PrintWriter
  • Properties 类
    • 看一个需求
      • 传统方法
    • 基本介绍
    • 读文件
    • 修改文件

温馨提示:师从韩顺平

文件

什么是文件

在这里插入图片描述

文件流

在这里插入图片描述

常用的文件操作

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

在这里插入图片描述

应用案例

在这里插入图片描述

package IO;

import org.junit.jupiter.api.Test;

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

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-26
 * @Description: no
 * @Version: 1.0
 */

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

    }
    //方式 1 new File(String pathname)
    @Test
    public void create01() {
        String filePath = "C:\\Users\\user\\Desktop\\Java\\File\\news1.txt";
        File file = new File(filePath);
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //方式 2 new File(File parent,String child) //根据父目录文件+子路径构建
    @Test
    public void create02() {
        File parentFile = new File("C:\\Users\\user\\Desktop\\Java\\File");
        String fileName = "news2.txt";
//这里的 file 对象,在 java 程序中,只是一个对象
//只有执行了 createNewFile 方法,才会真正的,在磁盘创建该文件
        File file = new File(parentFile, fileName);
        try {
            file.createNewFile();
            System.out.println("创建成功~");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //方式 3 new File(String parent,String child) //根据父目录+子路径构建
    @Test
    public void create03() {
        String parentPath = "C:\\Users\\user\\Desktop\\Java\\File";
        String fileName = "news4.txt";
        File file = new File(parentPath, fileName);
        try {
            file.createNewFile();
            System.out.println("创建成功~");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//下面四个都是抽象类
//
//InputStream
//OutputStream
//Reader //字符输入流
//Writer //字符输出流

}

获取文件的相关信息

在这里插入图片描述

应用案例

在这里插入图片描述

package IO;

import org.junit.jupiter.api.Test;

import java.io.File;

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-26
 * @Description: no
 * @Version: 1.0
 */

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

    }
    //获取文件的信息
    @Test
    public void info() {
//先创建文件对象
        File file = new File("C:\\Users\\user\\Desktop\\Java\\File\\news1.txt");
//调用相应的方法,得到对应信息
        System.out.println("文件名字=" + file.getName());  //文件名字=news1.txt

//getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory
        System.out.println("文件绝对路径=" + file.getAbsolutePath());  //文件绝对路径=C:\Users\\user\Desktop\Java\File\news1.txt

        System.out.println("文件父级目录=" + file.getParent());  //文件父级目录=C:\Users\\user\Desktop\Java\File

        System.out.println("文件大小(字节)=" + file.length());  //文件大小(字节)=0

        System.out.println("文件是否存在=" + file.exists());//T
        System.out.println("是不是一个文件=" + file.isFile());//T
        System.out.println("是不是一个目录=" + file.isDirectory());//F

    }
}

目录的操作和文件删除

在这里插入图片描述

应用案例

在这里插入图片描述

package IO;

import org.junit.Test;

import java.io.File;

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-26
 * @Description: no
 * @Version: 1.0
 */

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

    }
    @Test
    public void m1(){
        String filePath = "C:\\Users\\user\\Desktop\\Java\\File\\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("该文件不存在!");
        }
    }

    //在java编程中目录也被当做文件,只能删除空目录
    @Test
    public void m2(){
        String filePath = "C:\\Users\\user\\Desktop\\Java\\File";
        File file = new File(filePath);
        if(file.exists()){
            if(file.delete()){
                System.out.println(filePath+"删除成功");
            }else {
                System.out.println("删除失败!");
            }
        }else {
            System.out.println("该目录不存在!");
        }
    }
    @Test
    public void m3(){
        String diectoryPath = "C:\\Users\\user\\Desktop\\Java\\File\\file";
        File file = new File(diectoryPath);
        if(file.exists()){
            System.out.println(diectoryPath+"存在...");
        }else {
            if(file.mkdir()){
                System.out.println(diectoryPath+"创建成功");
            }else {
                System.out.println(diectoryPath+"创建失败");
            }
        }
    }
}

IO 流原理及流的分类

Java IO 流原理

在这里插入图片描述

IO流的分类

在这里插入图片描述

IO 流体系图-常用的类

IO 流体系图(重要!!!!!)

在这里插入图片描述

文件 VS IO流

文件是存储数据的地方,它在传输数据时,是以流的形式进行传输的
在这里插入图片描述

FileInputStream 介绍

在这里插入图片描述

简单案例

package IO;

import org.junit.jupiter.api.Test;

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

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

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

    }
    /**
     * 演示读取文件... * 单个字节的读取,效率比较低
     * -> 使用 read(byte[] b)
     */
    @Test
    public void readFile01() {
        String filePath = "C:\\Users\\user\\Desktop\\Java\\File\\news2.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 = "C:\\Users\\user\\Desktop\\Java\\File\\news2.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.println(new String(buf, 0, readLen));//显示
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//关闭文件流,释放资源.
        try {
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}

FileOutputStream 介绍

在这里插入图片描述

应用实例

package IO;

import org.junit.jupiter.api.Test;

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

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

public class FileOutput {
    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 = "hsp,world!";
//str.getBytes() 可以把 字符串-> 字节数组
//fileOutputStream.write(str.getBytes());
/*
write(byte[] b, int off, int len) 将 len 字节从位于偏移量 off 的指定字节数组写入此文件输出流
*/
            fileOutputStream.write(str.getBytes(), 0, 3);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

文件拷贝

编程完成图片/音乐 的拷贝

package IO;

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

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

public class FileCopy {
    public static void main(String[] args) {
//完成 文件拷贝,将 e:\\Koala.jpg 拷贝 c:\\
//思路分析
//1. 创建文件的输入流 , 将文件读入到程序
//2. 创建文件的输出流, 将读取到的文件数据,写入到指定的文件. 
        String srcFilePath = "e:\\Koala.jpg";
        String destFilePath = "e:\\Koala3.jpg";
        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 常用方法

在这里插入图片描述

应用案例

使用 FileReader 从 story.txt 读取内容,并显示

package IO;

import org.junit.jupiter.api.Test;

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

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

public class demo01 {
    public static void main(String[] args) {
    }
    /**
     * 单个字符读取文件
     */
    @Test
    public void readFile01() {
        String filePath = "C:\\Users\\user\\Desktop\\Java\\File\\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 {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 字符数组读取文件
     */
    @Test
    public void readFile02() {
        System.out.println("~~~readFile02 ~~~");
        String filePath = "C:\\Users\\user\\Desktop\\Java\\File\\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.println(new String(buf, 0, readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }}

使用 FileWriter 将 “风雨之后,定见彩虹” 写入到 note.txt 文件中

package IO;

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

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

public class deom02 {
    public static void main(String[] args) {
        String filePath = "C:\\Users\\user\\Desktop\\Java\\File\\note.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(" 你好北京~");
            fileWriter.write("风雨之后,定见彩虹");
         // 7) 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();
            }
*/
            try {
//fileWriter.flush();
//关闭文件流,等价 flush() + 关闭
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("程序结束...");
    }
}

节点流和处理流

基本介绍

在这里插入图片描述

节点流和处理流一览图

上面红色方框的是节点流,下面红色方框的是处理流

在这里插入图片描述

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

在这里插入图片描述

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

在这里插入图片描述

处理流-BufferedReader 和 BufferedWriter

在这里插入图片描述

package IO;

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

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

public class BufferReader_01 {
    public static void main(String[] args) throws Exception {
        String filePath = "e:\\a.java";
//创建 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) {
if (in == null)
return;
try {
in.close();//in 就是我们传入的 new FileReader(filePath), 关闭了. } finally {
in = null;
cb = null;
}
}
}
*/
        bufferedReader.close();
    }
}

在这里插入图片描述


```java
package IO流;

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

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

public class BufferWriter_01 {
    public static void main(String[] args) throws IOException {
        String filePath = "e:\\ok.txt";
//创建 BufferedWriter
//说明:
//1. new FileWriter(filePath, true) 表示以追加的方式写入
//2. new FileWriter(filePath) , 表示以覆盖的方式写入
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
        bufferedWriter.write("hello, 韩顺平教育!");
        bufferedWriter.newLine();//插入一个和系统相关的换行
        bufferedWriter.write("hello2, 韩顺平教育!");
        bufferedWriter.newLine();
        bufferedWriter.write("hello3, 韩顺平教育!");
        bufferedWriter.newLine();
//说明:关闭外层流即可 , 传入的 new FileWriter(filePath) ,会在底层关闭
        bufferedWriter.close();
    }
}

处理流-BufferedInputStream 和 BufferedOutputStream

在这里插入图片描述

package IO;

import java.io.*;

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

public class Copy {
    public static void main(String[] args) {
// String srcFilePath = "e:\\Koala.jpg";
// String destFilePath = "e:\\hsp.jpg";
// String srcFilePath = "e:\\0245_韩顺平零基础学 Java_引出 this.avi";
// String destFilePath = "e:\\hsp.avi";
        String srcFilePath = "e:\\a.java";
        String destFilePath = "e:\\a3.java";
//创建 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 readLen = 0;
//当返回 -1 时,就表示文件读取完毕
            while ((readLen = bis.read(buff)) != -1) {
                bos.write(buff, 0, readLen);
            }
            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

在这里插入图片描述

对象流介绍

在这里插入图片描述

package IO;

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

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

public class ObjectOutStream_ {
    public static void main(String[] args) throws Exception {
//序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
        String filePath = "e:\\data.dat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
//序列化数据到 e:\data.dat
        oos.writeInt(100);// int -> Integer (实现了 Serializable)
        oos.writeBoolean(true);// boolean -> Boolean (实现了 Serializable)
        oos.writeChar('a');// char -> Character (实现了 Serializable)
        oos.writeDouble(9.5);// double -> Double (实现了 Serializable)
        oos.writeUTF("韩顺平教育");//String
//保存一个 dog 对象
        oos.writeObject(new Dog1(10,"大黄"));
        oos.close();
        System.out.println("数据保存完毕(序列化形式)");
    }
}
class Dog1 implements Serializable {
    private String name;
    private int age;

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

在这里插入图片描述

package IO;

import java.io.*;

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

public class ObjectInputStream_ {
    public static void main(String[] args) throws Exception {
//序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
        String filePath = "e:\\data.dat";
        // 1.创建流对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src\\data.dat"));
// 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());
        System.out.println(ois.readObject());
        System.out.println(ois.readObject());  //这个就是 Object dog
        System.out.println(ois.readObject());
        //  小细节,如果要调用 Dog 方法,需要向下转型,或者啥的,只要代码中出现了这个类或者对象,就要把整个Dog移到可以引用的位置
        
// 3.关闭
        ois.close();
        System.out.println("以反序列化的方式读取(恢复)ok~");
    }
}

对象处理流使用细节

在这里插入图片描述

第五条解读:里面的属性,如果类型是一个自定义的类的话,也要求他实现序列化接口Serializable

标准输入输出流

在这里插入图片描述

System.in 			编译类型: InputStream    运行类型:BufferedInputStream
System.out 			编译类型: PrintStream    运行类型:PrintStream

转换流-InputStreamReader 和 OutputStreamWriter(解决中文乱码)

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

package IO;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

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

在这里插入图片描述

/ 1.创建流对象
OutputStreamWriter osw =
new OutputStreamWriter(new FileOutputStream("d:\\a.txt"), "gbk");
// 2.写入
osw.write("hello,韩顺平教育~");
// 3.关闭
osw.close();
System.out.println("保存成功~");

打印流-PrintStream 和 PrintWriter

在这里插入图片描述

PrintStream 案例

package IO;

import java.io.IOException;
import java.io.PrintStream; /**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */
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("john, hello");
//因为 print 底层使用的是 write , 所以我们可以直接调用 write 进行打印/输出
        out.write("韩顺平,你好".getBytes());
        out.close();
//我们可以去修改打印流输出的位置/设备
//1. 输出修改成到 "e:\\f1.txt"
//2. "hello, 韩顺平教育~" 就会输出到 e:\f1.txt
//3. public static void setOut(PrintStream out) {
// checkIO();
// setOut0(out); // native 方法,修改了 out
// }
        System.setOut(new PrintStream("e:\\f1.txt"));
        System.out.println("hello, 韩顺平教育~");
    }
}

PrintWriter 案例

package IO;

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

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

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

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

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

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("=");
//如果我们要求指定的 ip 值
            if ("ip".equals(split[0])) {
                System.out.println(split[0] + "值是: " + split[1]);
            }
        }
        br.close();
    }
}

基本介绍

在这里插入图片描述

读文件

package IO;

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

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

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

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

/**
 * @Author: 韩如意
 * @CreateTime: 2025-02-27
 * @Description: no
 * @Version: 1.0
 */

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);//如果是新 k, 就 addEntry
return null;
}
*/
        properties.setProperty("charset", "utf8");
        properties.setProperty("user", "汤姆");//注意保存时,是中文的 unicode 码值
        properties.setProperty("pwd", "888888");
//将 k-v 存储文件中即可
        properties.store(new FileOutputStream("src\\mysql2.properties"), null);
        System.out.println("保存配置文件成功~");
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2307425.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Spring Boot集成Jetty、Tomcat或Undertow及支持HTTP/2协议

目录 一、常用Web服务器 1、Tomcat 2、Jetty 3、Undertow 二、什么是HTTP/2协议 1、定义 2、特性 3、优点 4、与HTTP/1.1的区别 三、集成Web服务器并开启HTTP/2协议 1、生成证书 2、新建springboot项目 3、集成Web服务器 3.1 集成Tomcat 3.2 集成Jetty 3.3 集成…

《Python实战进阶》专栏 No 5:GraphQL vs RESTful API 对比与实现

《Python实战进阶》专栏包括68集&#xff0c;每一集聚焦一个中高级技术知识点&#xff0c;涵盖Python在Web开发、数据处理、自动化、机器学习、并发编程等领域的应用&#xff0c;系统梳理Python开发者的知识集。本集的主题为&#xff1a; No4 : GraphQL vs RESTful API 对比与实…

MYSQL 5.7数据库,关于1067报错 invalid default value for,解决方法!

???作者&#xff1a; 米罗学长 ???个人简介&#xff1a;混迹java圈十余年&#xff0c;精通Java、小程序、数据库等。 ???各类成品java毕设 。javaweb&#xff0c;ssm&#xff0c;springboot&#xff0c;mysql等项目&#xff0c;源码丰富&#xff0c;欢迎咨询。 ???…

【Linux基础】Linux下的C编程指南

目录 一、前言 二、Vim的使用 2.1 普通模式 2.2 插入模式 2.3 命令行模式 2.4 可视模式 三、GCC编译器 3.1 预处理阶段 3.2 编译阶段 3.3 汇编阶段 3.4 链接阶段 3.5 静态库和动态库 四、Gdb调试器 五、总结 一、前言 在Linux环境下使用C语言进行编程是一项基础且…

浅谈HTTP及HTTPS协议

1.什么是HTTP&#xff1f; HTTP全称是超文本传输协议&#xff0c;是一种基于TCP协议的应用非常广泛的应用层协议。 1.1常见应用场景 一.浏览器与服务器之间的交互。 二.手机和服务器之间通信。 三。多个服务器之间的通信。 2.HTTP请求详解 2.1请求报文格式 我们首先看一下…

Pytest自定义测试用例执行顺序

文章目录 1.前言2.pytest默认执行顺序3.pytest自定义执行顺序 1.前言 在pytest中&#xff0c;我们可能需要自定义测试用例的执行顺序&#xff0c;例如登陆前需要先注册&#xff0c;这个时候就需要先执行注册的测试用例再执行登录的测试用例。 本文主要讲解pytest的默认执行顺序…

人大金仓KCA | 用户与角色

人大金仓KCA | 用户与角色 一、知识预备1. 用户和角色 二、具体实施1. 用户管理-命令行1.1 创建和修改用户1.2 修改用户密码1.3 修改用户的并发连接数1.4 修改用户的密码有效期 2.用户管理-EasyKStudio2.1 创建和修改用户2.2 修改用户密码2.3 修改用户的并发连接数2.4 修改用户…

【Azure 架构师学习笔记】- Azure Databricks (12) -- Medallion Architecture简介

本文属于【Azure 架构师学习笔记】系列。 本文属于【Azure Databricks】系列。 接上文 【Azure 架构师学习笔记】- Azure Databricks (11) – UC搭建 前言 使用ADB 或者数据湖&#xff0c;基本上绕不开一个架构“Medallion”&#xff0c; 它使得数据管理更为简单有效。ADB 通过…

智能证件照处理器(深度学习)

功能说明:支持常见证件照尺寸(一寸、二寸、护照等) 智能背景去除(使用深度学习模型)自定义背景颜色选择自动调整尺寸并保持比例实时预览处理效果注意:整合rembg进行抠图,使用Pillow处理图像缩放和背景替换,定义常见证件照尺寸,并提供用户交互选项。首次运行时会自动下…

C++-第十三章:红黑树

目录 第一节&#xff1a;红黑树的特征 第二节&#xff1a;实现思路 2-1.插入 2-1-1.unc为红 2-1-2.cur为par的左子树&#xff0c;且par为gra的左子树(cur在最左边) 2-1-2-1.unc不存在 2-1-2-2.unc为黑 2-1-3.cur为par的右子树&#xff0c;且par为gra的右子树(cur在最右侧) 2-…

推荐3个背景渐变色的wordpress主题

干净、清爽、背景渐变色的wordpress企业主题 ​ 服务类公司wordpress企业主题https://www.jianzhanpress.com/?p8255 红色大气的wordpress企业主题&#xff0c;适合服务行业的公司搭建企业官方网站使用。 ​ wordpress询盘型独立站主题https://www.jianzhanpress.com/?p8258…

Scrapy:隧道代理中移除 Proxy-Authorization 的原理解析

隧道代理中移除 Proxy-Authorization 的原理解析 背景 在 Scrapy 的 HTTP 下载处理中&#xff0c;当使用隧道代理&#xff08;TunnelingAgent&#xff09;时&#xff0c;会移除请求头中的 Proxy-Authorization。这个操作看似简单&#xff0c;但背后有着重要的安全考虑和技术原…

微信小程序-二维码绘制

wxml <view bindlongtap"saveQrcode"><!-- 二维码 --><view style"position: absolute;background-color: #FFFAEC;width: 100%;height: 100vh;"><canvas canvas-id"myQrcode" style"width: 200px; height: 200px;ba…

Fiddler 的安装与使用

目录 1、Fiddler 的安装2、Fiddler 的使用 1、Fiddler 的安装 通过Fiddler 官网进行下载&#xff08;下载免费的经典版本&#xff09;&#xff0c;填写用途、邮箱、国家信息即可开始下载。 Fiddler 官网下载链接 双击安装包即可进行安装&#xff0c;显示以下界面说明安装成功。…

Hadoop架构详解

Hadoop 是一个开源的分布式计算系统&#xff0c;用于存储和处理大规模数据集。Hadoop 主要由HDFS&#xff08;Hadoop Distributed File System&#xff09;、MapReduce、Yarn&#xff08;Jobtracker&#xff0c;TaskTracker&#xff09;三大核心组件组成。其中HDFS是分布式文件…

清华大学DeepSeek文档下载,清华大学deepseek下载(完成版下载)

文章目录 前言一、清华大学DeepSeek使用手册下载二、清华大学DeepSeek使用手册思维导图 前言 这是一篇关于清华大学deepseek使用手册pdf的介绍性文章&#xff0c;主要介绍了DeepSeek的定义、功能、使用方法以及如何通过提示语设计优化AI性能。以下是对这些核心内容的简要概述&…

Hadoop第2课(伪分布式集群的搭建)

jdk和hadoop安装包&#xff1a; hadoop-2.9.2.t......等2个文件官方版下载丨最新版下载丨绿色版下载丨APP下载-123云盘 1、用XFTP发送hadoop安装包和jdk到/home/hadoop/目录下&#xff08;hadoop用户的主目录&#xff09; 2、解压jdk安装包到~目录 卸载jdk的命令&#xff1a;r…

使用Crawlee可破题js渲染采集数据

使用 Crawlee 实现自动化爬虫流程 1. Crawlee 简介 Crawlee 是一个强大的爬虫框架&#xff0c;用于快速构建和维护可靠的爬虫。它支持多种爬虫类型&#xff0c;包括基于 Cheerio 和 Playwright 的爬虫&#xff0c;能够高效处理静态和动态网页。 2. 项目目标 通过自动化脚本实…

Fiddler在Windows下抓包Https

文章目录 1.Fiddler Classic 配置2.配置浏览器代理自动代理手动配置浏览器代理 3.抓取移动端 HTTPS 流量&#xff08;可选&#xff09;解决抓取 HTTPS 失败问题1.Fiddler证书过期了 默认情况下&#xff0c;Fiddler 无法直接解密 HTTPS 流量。需要开启 HTTPS 解密&#xff1a; 1…

Java语法基础知识点1

目录 一、数组 1.1数组的初始化&#xff1a; 1.2数组的遍历方法&#xff1a; 1.3数组的常见使用方法&#xff1a; 二、类和对象 2.1构造方法&#xff1a; 2.2this关键字: 三、封装 3.1访问限定符&#xff1a; 3.2static关键字&#xff1a; 3.3代码块&#xff1a; 一…