吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 847|回复: 14
收起左侧

[学习记录] Java学习之IO流

[复制链接]
EXiaoLu 发表于 2022-7-23 11:47

IO流

其中的输入与输出是相对java程序而言,并且是以“流(steam)”的方式进行

java.io包下提供了各种“流”类和接口

创建文件

  • 创建文件对象

    • 方式1 new File(pathname) // 根据路径构建一个File对象
    • 方式2 new File(File parent,String child) // 根据父目录文件+子路径构建
    • 方式3 new File(String parent,String child) // 根据父目录+子路径构建
  • 创建新文件

    • 对象.createNewFile()

代码

package com.xiaolu.file_;

import org.junit.jupiter.api.Test;

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

/**
 * home.php?mod=space&uid=686208 林小鹿
 * home.php?mod=space&uid=1248337 1.0
 * 创建文件
 */
public class FileCreate {
    public static void main(String[] args) {

    }
    // 方式1 new File(pathname)
    @Test
    public void create01() throws IOException {
        String filePath = "D:\\1.txt";
        File file = new File(filePath);

        file.createNewFile();
        System.out.println("文件创建成功");
    }

    @Test
    // 方式2 new File(File parent,String child) // 根据父目录文件+子路径构建
    public void create02() {
        File parentFile = new File("D:\\");
        String fileName = "2.txt";
        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 = "d:\\";
        String fileName = "3.txt";
        File file = new File(parentPath, fileName);
        try {
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

相关方法

  • mkdir:创建目录
  • mkdirs:创建多级目录
  • 其余自行查找

流的分类

  • 按操作数据单位不同分为:字节流(8bt)二进制文件,字符流(按字符)文本文件
  • 按数据流的流向不同分为:输入流,输出流
  • 按流的角色的不同分为:节点流,处理流/包装流
(抽象基类) 字节流 字符流
输入流 InputStream Reader
输出流 OutputStream Writer

InputStream:字节输入流

  • InputStream抽象类是所有类字节输入流的超类
  • InputStream常用的子类
    • FilelnputStream:文件输入流
    • BufferedInputStream:缓冲字节输入流
    • ObjectInputStream:对象字节输入流

代码

package com.xiaolu.file_.inputstream_;

import org.junit.jupiter.api.Test;

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

/**
 * @author 林小鹿
 * @version 1.0
 * 字节输入流
 */
public class FileInputStream_ {
    public static void main(String[] args) {

    }

    /**
     * 单个字节的读取,效率比较低 -> 使用 read(byte[] b)来优化读取
     */
    @Test
    public void read01() {
        String filePath = "d:\\1.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            // 创建了 FileInputStream 对象,用于读取 文件
            fileInputStream = new FileInputStream(filePath);
            //从该输入流读取一个字节的数据。如果没有输入可用,此方法将阻止。
            //如何返回-1,表示读取完毕
            while ((readData = fileInputStream.read()) != -1) {
                System.out.print((char) readData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭文件流,释放资源
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 使用 read(byte[] b)来优化读取
     */
    @Test
    public void read02() {
        String filePath = "d:\\1.txt";
        int readLen = 0;
        byte[] buf = new byte[8]; // 一次读取8个字节

        FileInputStream fileInputStream = null;
        try {
            // 创建了 FileInputStream 对象,用于读取 文件
            fileInputStream = new FileInputStream(filePath);
            //从输入流读取一些字节数,并将它们存储到缓冲区b 。 实际读取的字节数作为整数返回。 该方法阻塞直到输入数据可用,检测到文件结束或抛出异常。
            //如何返回-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();
            }
        }

    }
}

FileOutputStream:字节输出流

讲数据写入到文件中,如果该文件不存在,则创建该文件

  • new FileOutputStream(filePath)创建方式,当写入内容是,会覆盖原来的内容
  • new FileOutputStream(filePath,true)创建方式,当写入内容是,是追加到文件后面

代码

package com.xiaolu.file_;

import org.junit.jupiter.api.Test;

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

/**
 * @author 林小鹿
 * @version 1.0
 */
public class FileOutputStrean_ {
    public static void main(String[] args) {

    }

    @Test
    public void writeFile() {
        // 创建FileOutputStream对象
        //1.new FileOutputStream(filePath)创建方式,当写入内容是,会覆盖原来的内容
        //2.new FileOutputStream(filePath,true)创建方式,当写入内容是,是追加到文件后面
        String filePath = "d:\\a.txt";
        FileOutputStream fileOutputStream = null;

        try {
//            fileOutputStream = new FileOutputStream(filePath);
            fileOutputStream = new FileOutputStream(filePath,true);
            // 写入一个字节
//            fileOutputStream.write('a');
            // 写入字符串
            String str = "hello,Linxiaolu!";
            // getBytes 可以把一个字符串转成字节数组
//            fileOutputStream.write(str.getBytes());  // 转成byte数组
            /*
            第三种方法
            write(byte[]b,int off,int len) 将Len字节从位于偏移量off的指定字节数组写入此文件输出流
             */
            fileOutputStream.write(str.getBytes(), 0, str.length());  // 等价于 fileOutputStream.write(str.getBytes())

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

文件拷贝案例

package com.xiaolu.file_;

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

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

        String srcFilePath = "C:\\Users\\lin\\Pictures\\wallhaven-pkgkkp.png";
        String destFilePath = "D:\\临时\\1.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相关方法

  1. new FileReader(File/String)
  2. read:每次读取单个字符,返回该字符,如果到文件末尾返回-1
  3. read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回-1相关API:
    1. new String(char[]):将char[]转换成String
    2. new String(char[],off,len):将char[]的指定部分转换成String

代码

package com.xiaolu.file_;

import org.junit.jupiter.api.Test;

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

/**
 * @author 林小鹿
 * @version 1.0
 * 字符流
 */
public class FileReader_ {
    public static void main(String[] args) {

    }

    /**
     * 单个字符读取
     */
    @Test
    public void reader01() {
        String filePath = "d:\\news.txt";
        // 1、创建FileReader 对象
        FileReader fileReader = null;
        int data = 0;
        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 reader02() {
        String filePath = "d:\\news.txt";
        // 1、创建FileReader 对象
        FileReader fileReader = null;
        int readLen = 0;
        char[] buf = new char[8];
        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常用方法

  1. new FileWriter(File/String):覆盖模式,相当于流的指针在首端
  2. new FileWriter(File/String,true):追加模式,相当于流的指针在尾端
  3. write(int):写入单个字符
  4. write(char[]):写入指定数组
  5. write(char[],off,len):写入指定数组的指定部分
  6. write(string):写入整个字符串
  7. write(string,,off,Ien):写入字符串的指定部分
    相关APl:String类:toCharArray:将String转换成char[

注意:
FileWriter使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件!

代码

package com.xiaolu.file_;

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

/**
 * @author 林小鹿
 * @version 1.0
 */
public class FileWriter_ {
    public static void main(String[] args) {
        String filePath = "d:\\临时\\note.txt";
        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("\n林小鹿ex".toCharArray(), 0, 4);
//            6)write(string):写入整个字符串
            fileWriter.write("老上海");
//            7)write(string,off,Len):写入字符串的指定部分
            fileWriter.write("进击的小鹿 ", 0, 4);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // fileWriter.flush();
                // 关闭文件流,等价于 flush + 关闭
                fileWriter.close();
                System.out.println("程序结束");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

节点流和处理流

  • 节点流可以从一个特定的数据源读写数据,如FileReader、.FileWriter[源码]
    • 灵活性低,只能针对特定的数据进行操作
  • 处理流(也叫包装流)是“连接”在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,如BufferedReader、BufferedWriter[源码]
    • 可操作实现了Reader类的所有数据类型,可对节点流进行一个包装,提高灵活性

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

  1. 节点流是底层流/低级流,直接跟数据源相接。
  2. 处理流包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出。[源码理解]
  3. 处理流(也叫包装流)对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连[模拟修饰器设计模式]

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

  • 性能的提高:主要以增加缓冲的方式来提高输入输出的效率。
  • 操作的便捷:处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活方便

处理流-BufferedReader和BufferedWriter

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

底层还是节点流

BufferedReader代码

package com.xiaolu.file_;

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

/**
 * @author 林小鹿
 * @version 1.0
 */
public class BufferedReader_ {
    public static void main(String[] args) throws Exception {
        String filePath = "d:\\news.txt";
        // 创建bufferedReader
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        // 读取
        String line; // 按行读取,效率高
        // bufferedReader.readLine是按行读取文件,当返回null时,表示文件读取完毕
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }

        // 关闭流,这里只需要关闭 BufferedReader,因为底层会自动去关闭 节点流(FileReader)
        bufferedReader.close();
    }
}

BufferedWriter代码

package com.xiaolu.file_;

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

/**
 * @author 林小鹿
 * @version 1.0
 */
public class BufferedWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\ok.txt";
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
//        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath, true));  // 追加
        bufferedWriter.write("你好,世界");
        bufferedWriter.newLine();  // 插入一个和系统相关的换行符
        bufferedWriter.write("你好,世界");
        bufferedWriter.newLine();
        bufferedWriter.write("你好,世界");
        bufferedWriter.newLine();

        // 关闭
        bufferedWriter.close();

    }
}

案例

package com.xiaolu.file_;

import java.io.*;

/**
 * @author 林小鹿
 * @version 1.0
 * BufferedReader和BufferedWriter是按照字符操作,不要去操作二进制文件[声音,视频,doc,pdf,图片等等],可能造成文件损坏
 */
public class BufferedCopy_ {
    public static void main(String[] args) {
        String srcFilePath = "d:\\ok.txt";
        String destFilePath = "d:\\python\\ok2.txt";
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        String line;

        try {
            bufferedReader = new BufferedReader(new FileReader(srcFilePath));
            bufferedWriter = new BufferedWriter(new FileWriter(destFilePath));
            // readLine 是读取一行的内容,但是没有换行符
            while ((line = bufferedReader.readLine()) != null) {
                bufferedWriter.write(line);
                // 插入一个换行符
                bufferedWriter.newLine();
            }
            System.out.println("拷贝完毕~");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

处理流-BufferedInputStream和BufferedOutputStream

  • BufferedInputStream是字节流在创建BufferedInputStream时,会创建一个内部缓冲区数组
  • BufferedOutputStream是字节流,实现缓冲的输出流,可以将多个字节写入底层输出流中,而不必对每次字节写入调用底层系统

案例代码

package com.xiaolu.file_;

import java.io.*;

/**
 * @author 林小鹿
 * @version 1.0
 * 拷贝视频、图片等二进制文件
 * 同样也可以操作文本文件,因为都是安装字节来操作的
 */
public class BufferedCopy02 {
    public static void main(String[] args){
    String srcFilePath = "d:\\python\\1.png";
    String destFilePath = "d:\\python\\2.jpg";
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(srcFilePath));
            bos = new BufferedOutputStream(new FileOutputStream(destFilePath));

            // 循环的读取文件,并写入到 destFilePath
            // 创建缓存,提高效率
            byte[] buff = new byte[1024];
            int readLen = 0;

            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

  • 序列化和反序列化
    • 序列化就是在保存数据时,保存数据的值数据类型
    • 反序列化就是在恢复数据时,恢复数据的值数据类型
    • 需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的该类必须实现如下两个接口之一:
    • Serializable   // 这是一个标记接口,没有方法
    • Externalizable  // 该接口有方法需要实现,因此我们一般实现上面的Serializable接口

ObjectOutputStream代码

package com.xiaolu.file_;

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

/**
 * @author 林小鹿
 * @version 1.0
 * 序列化
 */
public class ObjectOutputStream_ {
    public static void main(String[] args) throws Exception {
        // 序列化后,保存的文件格式,不是纯文本,而是按照他的格式来保存的
        String filePath = "d:\\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 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;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

ObjectInputStream代码

package com.xiaolu.file_;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 * @author 林小鹿
 * @version 1.0
 * 反序列化
 */
public class ObjectInputStream_ {

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

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

        // 读取(反序列化)的顺序需要和你保存数据(序列化)的顺序一致,否则会出现异常
        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,dog 的运行类型是Dog
        //1.如果我们希望调用Dog的方法,需要向下转型
        //2.需要我们将Dog类的定义,拷贝到可以引用的位置
        Object dog = ois.readObject();
        System.out.println("运行类型=" + dog.getClass());
        System.out.println(dog); // 底层 Object -> Dog

        // 关闭
        ois.close();
    }
}

细节

  • 读写顺序要一致
  • 要求实现序列化或反序列化对像,需要实现Serializable
  • 序列化的类中建议添加SerialVersionUID,为了提高版本的兼容性
  • 序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员
  • 序列化对象时,要求里面属性的类型也需要实现序列化接口
  • 序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实
    现了序列化

标准输入\输出流

  • System.in
    • 类型为:InputStream
    • System.in    编译类型:Inputstream
      System.in    运行类型:BufferedInputstream
      表示的是标准输入  键盘
  • System.out
    • 类型为:PrintStream
    • 编译类型Printstream
      运行类型PrintStream
      表示标准输出  显示器

转换流-InputStreamReader和OutputStreamWriter

用于字节流转换成字符流

  • InputStreamReader:Readert的子类,可以将InputStream(字节流)包装成Reader(字符流)
  • OutputStreamWriter:Writert的子类,实现将OutputStream(字节流)包装成Vriter(字符流)
  • 当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
  • 可以在使用时指定编码格式比如utf-8,gbk,gb2312,ISO8859-1等)

InputStreamReader代码

package com.xiaolu.file_;

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

/**
 * @author 林小鹿
 * @version 1.0
 * 演示使用InputStreamReader转换流解决中文乱码问题
 * 将字节流FileInputStream转成字符流InputStreamReader,指定编码gbk/utf-8
 */
public class InputStreamReader_ {
    public static void main(String[] args) throws Exception{
        String filePath = "d:\\ok.txt";
        //1.把FileInputStream转成InputStreamReader
        //2.指定编码gbk
        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
        // 3.最后,使用处理流 BufferedReader 处理,把InputStreamReader传入BufferedReader
        BufferedReader br = new BufferedReader(isr);
        // 4.读取
        String s = br.readLine();
        System.out.println("读取到的内容=" + s);
        // 5.关闭
        br.close();

    }
}

OutputStreamWriter代码

package com.xiaolu.file_;

import org.junit.jupiter.api.condition.OS;

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

/**
 * @author 林小鹿
 * @version 1.0
 * 把FileOutputStream字节流,转成字符流OutputStreamWriter
 * 指定处理的编码gbk/Utf-8/Utf8
 */
public class OutputStreamWriter_ {

    public static void main(String[] args) throws IOException {
        String filePath = "d:\\python\\0.txt";
        String charSet = "gbk";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
        osw.write("进击的小鹿");
        osw.close();
        System.out.println("按照" + charSet + "保存文件成功");
    }
}

打印流-PrintStream和PrintWriter

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

在默认情况下,Printstream输出数据的位置是标准输出,即显示器

PrintStream代码

package com.xiaolu.file_;

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

/**
 * @author 林小鹿
 * @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.输出修改成到"d:\\f1.txt"
        //2."hello,林小鹿~"就会输出到e:\f1.txt
        //3.public static void setOut(PrintStream out){
                //checkI0();
                //setOvt0(out); // native方法,修改了out
        // }
        System.setOut(new PrintStream("d:\\f1.txt"));
        System.out.println("hello,林小鹿~");
    }

}

PrintWriter代码

package com.xiaolu.file_;

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

/**
 * @author 林小鹿
 * @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("d:\\f2.txt"));

        printWriter.println("你好");
        // 不关闭流的话无法写入
        printWriter.close();

    }
}

Properties类

Properties父类是Hashtable,底层就是Hashtable核心方法

  1. 专门用于读写配置文件的集合类
    • 配置文件的格式:
      键=值
      键=值
  2. 注意:键值对不需要有空格,值不需要用引号一起来。默认类型是String
  3. Properties的常见方法
    • Ioad:加载配置文件的键值对到Properties对象
    • Iist:将数据显示到指定设备/流对象
    • getProperty(key):根据键获取值
    • get(key):根据键获取值
    • setProperty(key,value):设置键值对到Properties对象,若不存在则添加
    • store:将Propertiest中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会存储为unicode码

代码

package com.xiaolu.properties_;

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

/**
 * @author 林小鹿
 * @version 1.0
 * Properties父类是Hashtable,底层就是Hashtable核心方法
 */
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) {
////            System.out.println(line);
//            String[] split = line.split("=");
//            System.out.println(split[0] + "的值是:"+split[1]);
//        }
//        br.close();

        // 使用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);

        // 创建、添加、修改
        properties.setProperty("charSet", "utf8");
        properties.setProperty("user", "汤姆"); // 中文的话保存的是中文的 unicode码值
        // 存储
//        properties.store(new FileOutputStream("src\\mysql2.properties"), null); // 这里的null为注释,可置为空值
        properties.store(new FileOutputStream("src\\mysql2.properties"), "This is a comment and can be set to null");
        System.out.println("存储成功~~~");

    }
}

案例代码

案例一

package com.xiaolu.file_.homework;

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

/**
 * @author 林小鹿
 * @version 1.0
 * 文件创建并写入数据
 */
public class work01 {
    public static void main(String[] args) throws IOException {
        String directorPath = "d:\\python\\mytemp";
        File file = new File(directorPath);
        if (!(file.exists())) {
            // 创建
            if (file.mkdirs()) {
                System.out.println("创建"+directorPath+"创建成功");
            }else {
                System.out.println("创建"+directorPath+"创建失败");
            }
        }

        String filePath = directorPath + "\\hello.txt";
        file = new File(filePath);
        if (!(file.exists())) {
            // 创建文件
            if (file.createNewFile()) {
                System.out.println(filePath + "创建成功~");
                BufferedWriter bw = new BufferedWriter(new FileWriter(file));
                bw.write("hello,world~~ 林小鹿");
                bw.close();
            }else {
                System.out.println(filePath + "创建失败~");
            }
        }else {
            System.out.println(filePath + "已经存在,不再重复创建");
        }

    }
}

案例二

package com.xiaolu.file_.homework;

import org.junit.jupiter.api.Test;

import javax.swing.plaf.synth.SynthOptionPaneUI;
import java.io.*;
import java.util.Properties;

/**
 * @author 林小鹿
 * @version 1.0
 */
public class work02 {
    public static void main(String[] args) throws IOException {
        String filePath = "src\\mysql.properties";
        Properties properties = new Properties();
        properties.load(new FileReader(filePath));
        String name = properties.get("name") + "";
        int age = Integer.parseInt(properties.get("age") + "");
        String color = properties.get("color") + "";

        Dog dog = new Dog(name, age, color);
        System.out.println(dog);
        //将创建的Dog对象,序列化到文件dog.dat文件
        String serFilePath = "src\\dog.dat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFilePath));
        oos.writeObject(dog);
        oos.close();
        System.out.println("dog对象序列化完成...");

    }

    @Test
    public void m1() throws IOException, ClassNotFoundException {
        String serFilePath = "src\\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;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }
}

免费评分

参与人数 3吾爱币 +1 热心值 +2 收起 理由
pikachu2022 + 1 mark,收藏了
bakaest + 1 很棒
Alexwhich + 1 谢谢@Thanks!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

chase001 发表于 2022-7-23 12:39
mark,不错的学习下
Nemoris丶 发表于 2022-7-23 12:44
Stkj 发表于 2022-7-23 13:41
alexonetwo 发表于 2022-7-23 13:57
io流这个东西用的不多
sxz123sxz 发表于 2022-7-23 14:33
感谢分享
liunianmeng 发表于 2022-7-23 14:48
感谢分享
wjc 发表于 2022-7-23 15:33

感谢分享收藏了
diwun 发表于 2022-7-23 17:01
最近正在学,感谢分享!
ammo 发表于 2022-7-23 17:39
其实引入common io包就很方便
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止回复与主题无关非技术内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-6-4 18:00

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表