Java筑基32-IO流02-节点流&处理流

目录

节点流和处理流

1.处理流设计模式

2. IO流设计模式-装饰器模式模拟

3. BufferedReader & BufferedWriter

4. Buffered拷贝(字符文件)

5. Buffered字节处理流

6.Buffered拷贝(字节文件)

7.对象处理流

8.标准输入输出流

转换流

1)乱码问题引出转换流

2)InputStreamReader&OutputStreamWriter

打印流PrintStream&PrintWriter

1)PrintStream

2)PrintWriter

Properties类

1)配置文件引出Properties

2)Properties类

案例

1)目录文件操作

2)读取文件操作


节点流和处理流

1.处理流设计模式

2. IO流设计模式-装饰器模式模拟

/**
* @author:飞扬
* @公众hao:程序员飞扬
* @description: IO流设计模式-装饰器模式模拟
*/
public abstract class Reader_ {
    
    //抽象类,提供两个空方法
    public void readFile(){}
    
    public void readString(){}
}

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description: IO流设计模式-装饰器模式模拟
 */
public class FileReader_ extends Reader_{

    //模拟节点流,读取文件
    @Override
    public void readFile(){
        System.out.println("读取文件。。。");
    }
}
/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description: IO流设计模式-装饰器模式模拟
 */
public class StringReader_ extends Reader_{

    //模拟节点流,处理字符串
    @Override
    public void readString(){
        System.out.println("读取字符串。。。");
    }
}
/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description: IO流设计模式-装饰器模式模拟
 *
 * 模拟处理流/包装流
 */
public class BufferedReader_ extends Reader_{

    private Reader_ reader_;

    public BufferedReader_(Reader_ reader_) {
        this.reader_ = reader_;
    }

    //原始方法
    public void readFile(){
        reader_.readFile();
    }

    public void readString(){
        reader_.readFile();
    }

    //扩展方法,多次读取文件(也可以加缓冲byte[]等)
    public void readFile(int num){
        for (int i = 0; i < num; i++) {
            reader_.readFile();
        }
    }

    //扩展方法,多次读取字符串(也可以批量读取字符串)
    public void readString(int num){
        for (int i = 0; i < num; i++) {
            reader_.readString();
        }
    }
}
/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description: 装饰器模式模拟测试
 */
public class Test_ {
    public static void main(String[] args) {
        BufferedReader_ bufferedReader_ = new BufferedReader_(new FileReader_());
        bufferedReader_.readFile(); //调原始方法
        System.out.println("----");
        bufferedReader_.readFile(3); //调扩展方法

        BufferedReader_ bufferedReader_1 = new BufferedReader_(new StringReader_());
        bufferedReader_1.readString(); //调原始方法
        System.out.println("----");
        bufferedReader_1.readString(5); //调扩展方法

    }
}

重点理解体会修饰器模式设计思想的巧妙。

3. BufferedReader & BufferedWriter

案例:使用BufferedReader读取文本文件

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

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description:
 */
public class BufferedReaderTest {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\hello.txt";

        //创建BufferedReader
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));

        //按行读取,效率高
        String line;

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

        //关闭流,这里注意,只需要关闭最外层流,因为底层会自动关闭节点流(追源码)
        bufferedReader.close();
    }
}

BufferedWriter写文件

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

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description:
 */
public class BufferedWriterTest {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\栓克油.txt";
        //BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath)); //会覆盖
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath,true)); //追加模式

        bufferedWriter.write("hello,");
        bufferedWriter.newLine();
        bufferedWriter.write("飞扬");

        bufferedWriter.close();
    }
}

4. Buffered拷贝(字符文件)

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

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description:
 */
public class BufferedCopy {

    public static void main(String[] args) {

        String srcFilePath = "d:\\hello.txt";
        String destFilePath = "d:\\bufferedCopy.txt";

        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;

        try{
            bufferedReader = new BufferedReader(new FileReader(srcFilePath));
            bufferedWriter = new BufferedWriter(new FileWriter(destFilePath));

            String line;
            while((line = bufferedReader.readLine()) != null){
                bufferedWriter.write(line);
                bufferedWriter.newLine();
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(bufferedWriter != null){
                    bufferedWriter.close();
                }
                if(bufferedWriter != null){
                    bufferedWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}

5. Buffered字节处理流

6.Buffered拷贝(字节文件)

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

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description: 字节流拷贝(拷贝二进制文件,如图片,音视频等)
 *
 * 思考:字节流可以操作二进制文件,可以操作文本文件吗,当然可以。。。
 */
public class BufferedCopy2 {
    public static void main(String[] args) {

        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try{
            FileInputStream fis = new FileInputStream("d:\\aaa.jpg");
            FileOutputStream fos = new FileOutputStream("d:\\aaa2.jpg");
            bufferedInputStream = new BufferedInputStream(fis);
            bufferedOutputStream = new BufferedOutputStream(fos);
            
            byte[] b = new byte[1024];

            int len;
            while((len=bufferedInputStream.read(b)) != -1){
                bufferedOutputStream.write(b,0,len);
            }
            System.out.println("拷贝完成~~");
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if(bufferedOutputStream !=null) {
                    bufferedOutputStream.close();
                }
                if(bufferedInputStream != null){
                    bufferedInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

7.对象处理流

先回忆下什么是序列化和反序列化

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

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description: 序列化演示
 */
public class ObjectOutputStream_ {
    public static void main(String[] args) {
        String path = "d:\\data.dat";

        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
            oos.writeInt(100);  //将整型值100写入流中
            oos.writeBoolean(true);
            oos.writeChar('a');
            oos.writeDouble(9.5);
            oos.writeObject(new Dog("旺财",3));

            oos.close();
            System.out.println("序列化输写文件完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

class Dog implements Serializable {
    private String name;
    private Integer age;

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

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

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

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description:
 */
public class ObjectInputStream_ {
    public static void main(String[] args) {
        String path = "d:\\data.dat";

        try {
            //创建流对象
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
            
            //读取,注意事项
            System.out.println(ois.readInt());
            System.out.println(ois.readBoolean());
            System.out.println(ois.readChar());
            System.out.println(ois.readDouble());
            System.out.println(ois.readObject());
            
            //关闭
            ois.close();

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

    }
}

对象处理流注意事项:

8.标准输入输出流

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description:标准输入输出流
 */
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());


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

        Scanner scanner = new Scanner(System.in);
        System.out.println("输入内容:");
        String next = scanner.next();
        System.out.println("next=" + next);

    }
}

class java.io.BufferedInputStream

class java.io.PrintStream

输入内容:

你好,上海

next=你好,上海

转换流

1)乱码问题引出转换流

文件内容和编码如下:

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

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description: 乱码问题引出转换流
 */
public class CodeQuestion {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\hello.txt";
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        String s = bufferedReader.readLine();
        System.out.println("读取到的内容:" + s);
        bufferedReader.close();

    }
}

运行输出:

读取到的内容:aaa����

发现出现了乱码。

2)InputStreamReader&OutputStreamWriter

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description: 字节输入流(转换流)
 */
public class InputStreamReader_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\hello.txt";

        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath),"gbk");
        BufferedReader bufferedReader = new BufferedReader(isr);
        String s = bufferedReader.readLine();
        System.out.println("读取内容=" + s);

    }
}

输出:读取内容=aaa飞扬

不再出现乱码

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

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description: 直接输出流(转换流)
 */
public class OutputStreamReader_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\feiyang.txt";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath),"gbk");
        osw.write("hello,飞扬");

        osw.close();
    }
}

执行结果,生成指定编码的文件,不会乱码

打印流PrintStream&PrintWriter

1)PrintStream

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

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description:    打印流
 */
public class PrintStream_ {
    public static void main(String[] args) throws IOException {
        PrintStream out = System.out;
        out.print("hello,tom");

        //也可以直接调用write()打印/输出
        out.write("hello,tom".getBytes());
        out.close();

        //可以去修改打印输出的位置/设备
        System.setOut(new PrintStream("d:\\f1.txt"));
        System.out.println("hello,峰峰,你可长点心吧");
    }
}

输出结果:

2)PrintWriter

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description: 打印流PrintWriter
 */
public class PrintWriter_ {
    public static void main(String[] args) throws IOException {
        PrintWriter printWriter = new PrintWriter(new FileWriter("d:\\abc.txt"));
        printWriter.print("你好,上海");
        printWriter.close(); //注意,必须关闭流才会写入
    }
}

输出结果:

Properties类

1)配置文件引出Properties

新增文件:

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description:
 */
public class Properties01 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("src\\mysql.properties"));
        String line = "";
        while((line = br.readLine()) != null){
            String[] s = line.split("=");
            System.out.println(s[0]+"的值为"+s[1]);
        }
    }
}

打印输出:

user的值为root

password的值为123456

url的值为jdbc:mysql://localhost:3306/testdb

driver的值为com.mysql.jdbc.Driver

结论:读写麻烦,不方便

2)Properties类

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

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description:使用Properties类来读取文件
 */
public class Properties02 {
    public static void main(String[] args) throws IOException {
        //创建Properties对象
        Properties properties = new Properties();

        //加载指定配置文件
        properties.load(new FileReader("src\\mysql.properties"));

        //把k-v显示控制台
        properties.list(System.out);    //获取列表集合

        //根据key获取对应的值
        String url = properties.getProperty("url"); //获取指定属性
        System.out.println(url);

    }
}

打印输出:
-- listing properties --

user=root

password=123456

url=jdbc:mysql://localhost:3306/testdb

driver=com.mysql.jdbc.Driver

jdbc:mysql://localhost:3306/testdb

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

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description:使用Properties类保存配置文件,修改配置文件
 */
public class Properties03_ {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        properties.setProperty("charset","utf-8");
        properties.setProperty("user","汤姆");//此处保存的是unicode编码
        properties.setProperty("pwd","666");

        properties.setProperty("pwd","888"); //修改属性值(没有该属性就新增,有就修改)

        properties.store(new FileOutputStream("src\\mysql03.properties"),null);//保存
        properties.store(new FileOutputStream("src\\mysql03.properties"),"这是一个注释");//保存(指定注释)
        System.out.println( "保存配置文件成功~");
    }
}

执行结果:

案例

1)目录文件操作

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

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description:
 */
public class Homework01 {
    public static void main(String[] args) throws IOException {

        String direPath = "d:\\mytemp";
        File file = new File(direPath);
        if(file.exists()){
            System.out.println("目录已经存在");
        }else{
            boolean mkdir = file.mkdir();
            if(!mkdir){
                System.out.println("创建" + direPath +"目录失败");
            }else{
                System.out.println("创建" + direPath +"目录成功");
            }
        }

        String filePath = direPath + "\\homework01.txt";

        File file1 = new File(filePath);
        if(file1.exists()){
            System.out.println("文件" + filePath + "已存在");
        }else{
            if(file1.createNewFile()){
                System.out.println("创建" + filePath + "成功");

                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));
                bufferedWriter.write("我要学java");
                bufferedWriter.close();
                System.out.println("文件写入成功");
            }else{
                System.out.println(filePath + "创建失败");

            }
        }
    }

}

运行结果:

2)读取文件操作

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

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description: 读取文件操作
 */
public class Homework02 {
    public static void main(String[] args) {
        String filePath = "D:\\homework02.txt";
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(filePath));

            String line = "";
            int num = 0;
            while ((line = br.readLine()) != null) {
                System.out.println(++num + line);
            }

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

    }
}

运行结果:

3)Properties&序列化

package com.feiyang.basic15_file;

import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Properties;

/**
 * @author:飞扬
 * @公众hao:程序员飞扬
 * @description: 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.getProperty("name") + "";
        int age = Integer.parseInt(properties.getProperty("age") + "");
        String color = properties.getProperty("color") + "";

        Dog dog = new Dog(name, age, color);
        System.out.println(dog);

        //序列化对象
        String serFilePath = "d:\\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 = "d:\\dog.dat";
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(serFilePath));
        Dog dog = (Dog)objectInputStream.readObject();
        System.out.println(dog);
    }

}

class Dog implements Serializable {
    private String name;
    private int age;
    private String color;

    public Dog() {
    }

    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
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员飞扬

赠人玫瑰,手有余香,感谢支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值