JAVASE —— 10 IO流

文件

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

  • 输入流:数据从数据源(文件)到程序(内存)的路径

  • 输出流:数据从程序(内存)到数据源(文件)的路径

创建文件

  • new File(String pathname) //根据路径构建一个File对象

    public void create01() {
        String filePath = "D:\\fh\\practice\\src\\com\\fh\\file\\news1.txt";
        File file = new File(filePath);
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • new File(File parent,String child) //根据父目录文件+子路径构建

public void create02() {
        File parentFile = new File("D:\\fh\\practice\\src\\com\\fh\\file\\");
        String fileName = "news2.txt";
        //此步骤只是在内存里创建了一个file对象
        //只有后面执行createNewFile()才能真正在磁盘创建该文件
        File file = new File(parentFile, fileName);
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • new File(String parent,String child) //根据父目录+子路径构建

public void create03() {
        String parentPath = "D:\\fh\\practice\\src\\com\\fh\\file\\";
        String fileName = "news3.txt";
        File file = new File(parentPath, fileName);
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

获取文件信息

  • 方法:getName、getAbsolutePath、getParent、length、exists、isFile、isDirectory

常用的文件操作

  • mkdir():创建一级目录

  • mkdirs():创建多级目录

  • delete():删除空目录或文件


IO流原理及分类

  • I/O技术用于处理数据传输,如读/写文件、网络通讯等。

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

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

流的分类

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

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

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

ps:不能用字符流操作二进制文件(声音、视频、doc、pdf等等),可能造成文件损坏。字节流可以操作二进制二进制文件和文本文件。

  1. Java的IO流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的。

  1. 由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。


FileInputStream

//读取hello.txt文件中的数据
public void readFile01() throws IOException {
        String filePath = "d:\\hello.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            //创建FileInputStream对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);
            //从该输入流读取一个字节的数据。如果没有输入可用,此方法将阻止。
            //如果返回-1,表示读取完毕
            while ((readData = fileInputStream.read())!= -1){
                System.out.print((char)readData);

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

    }

FileOutputStream

  • new FileOutputStream(filePath)方式,会覆盖原来的内容

  • new FileOutputStream(filePath, true)会追加到文件后面

//将数据写到文件中,如果该文件不存在,则创建该文件
 public void writeFile() throws IOException {
        String filePath = "d:\\a.txt";
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(filePath);
            //写入一个字节
            fileOutputStream.write('a');
            //写入字符串
            String str = "hello,world";
            fileOutputStream.write(str.getBytes());

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

    }

文件拷贝

public static void main(String[] args) throws IOException {
        //完成文件拷贝
        //1.创建文件的输入流,将文件读入到程序
        //2.创建文件的输出流,将读取到的文件数据写入到指定的文件(读入部分就写入,使用循环操作)
        String srcFilePath = "d:\\pqt.png";
        String destFilePath = "d:\\pqt2.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.write(buf,0,readLen);

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileInputStream!=null) {
                fileInputStream.close();
            }
            if(fileOutputStream!=null) {
                fileOutputStream.close();
            }
        }

    }

FileReader

  • 方法:

  • new FileReader(File/String)

  • read:每次读取单个字符,返回该字符,如果到文件末尾返回-1

  • read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾则返回-1

  • API:

  • new String(char[]):将char[]转换成String

  • new String(char[], off, len):将char[]的指定部分转换成String

FileWriter

  • 方法:

  • new FileWriter(File/String):覆盖模式,相当于流的指针在首端

  • new FileWriter(File/String, true):追加模式,相当于流的指针在尾端

  • write(int):写入单个字符

  • write(char[]):写入指定数组

  • write(char[],off,len):写入指定数组的指定部分

  • write(string):写入整个字符串

  • write(string,off,len):写入字符串的指定部分

  • API:

  • String类:toCharArray:将String转换成char[]

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


节点流 和 处理流

  • 节点流可以从一个特定的数据源(文件、数组、管道、字符串等)读写数据,如FileReader、FileWriter

  • 处理流(也叫包装流)是“连接”已存在的流(节点流或处理流之上),为程序提供更强大的读写功能,也更加灵活,如BufferedReader、BufferedWriter

  • BufferedReader类中,有属性Reader,即可以封装一个节点流,该节点流可以是任意的,只要是Reader子类

  • 可以处理文件、或其他数据源

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

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

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

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

使用Reader类提供两个方法,readFile和readString,让下面两个子类FileReader和StringRead去实现,使用BufferedRead包装类包含一个reader属性,这样就可以接收Reader子类对象,这样就可以在下面进行Reader方法的调用和扩展。

处理流的功能主要体现在:

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

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

处理流

BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));

ps:关闭处理流时,只需要关闭外层流即可。


对象处理流

  • 需要保存值和数据类型时,需要用对象处理流操作,即将 基本数据类型 或 对象 进行 序列化 和 反序列化 操作。

序列化和反序列化

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

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

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

  • Seializable //这是一个标记接口

  • Externalizable //该接口有方法需要实现,因此一般实现Seializable接口

ObjectOutputStream

public class ObjectOutStream_ {
    public static void main(String[] args) {
        //序列化后,保存的文件格式,不是存文本,而是按照他的格式来保存
        String filePath = "d:\\data.dat";
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
            //序列化数据到 d:\\data.dat
            oos.write(100); //int->Integer (实现了 Serializable)
            oos.writeBoolean(true); //boolean->Boolean (实现了 Serializable)
            oos.writeChar('a'); //char->Character (实现了 Serializable)
            oos.writeUTF("hello涵宝宝"); //String
            //保存一个dog对象
            oos.writeObject(new Dog("旺财",10));
            oos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

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

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

ObjectInputStream

public class ObjectInputStream_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //指定反序列化的文件
        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.readUTF());
        System.out.println(ois.readObject());

        ois.close();
    }
}
class Dog implements Serializable {
    private String name;
    private int age;

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

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

注意事项和细节说明

  1. 读写顺序要一致

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

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

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

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

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

System.in和System.out

  • System.in

  • 编译类型:InputStream

  • 运行类型:BufferedInputStream

  • 表示的是标准输入 键盘

  • System.out

  • 编译类型:PrintStream

  • 运行类型:PrintStream

  • 表示的是标准输出 显示器


转换流

InputStreamReader和OutputStreamWriter

  • InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成(转换)Reader(字符流)

  • OutputStreamWriter:Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流)

  • 当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流

  • 可以在使用时指定编码格式(比如utf-8, gbk , gb2312, ISO8859-1等)

InputStreamReader

public class InputStreamReader_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\ok.txt";
        //1.把FileInputStream转成InputStreamReader
        //2.指定编码 gbk
        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "UTF-8");
        //3.把InputStreamReader传入BufferedReader
        BufferedReader br = new BufferedReader(isr);
        //4.读取
        String s = br.readLine();
        System.out.println("读取内容:"+s);
        br.close();
    }
}

OutputStreamReader

public class OutputStreamWriter_ {
    public static void main(String[] args) throws IOException {
        String filePath = "d:\\fh.txt";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath),"utf8");
        osw.write("Hi,付涵小美女~~~");
        osw.close();

    }
}

打印流

PrintStream和PrintWriter

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

PrintStream

public class PrintStream_ {
    public static void main(String[] args) throws IOException {
        PrintStream out = System.out;
        //在默认情况下,PrintStream输出数据的位置是 标准输出,即显示器
        out.print("hello");
        //因为print底层使用的是write,所以我们可以直接调用write进行打印/输出
        out.write("hello,小姐姐!".getBytes());
        //修改打印流输出的位置/设备 到 d:\fh1.txt
        System.setOut(new PrintStream("d:\\fh1.txt"));
        System.out.println("hello,世界");
        out.close();
    }
}

PrintWriter

public class PrintWriter_ {
    public static void main(String[] args) {
        //PrintWriter printWriter = new PrintWriter(System.out);
        //printWriter.print("hi,你好");
        try {
            PrintWriter printWriter = new PrintWriter(new FileWriter("d:\\fh2.txt"));
            printWriter.print("hi,你好");
            //一定要close,才会刷新
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

Properties

  • Properties的常见方法:

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

  • list:将数据显示到指定设备/流对象

  • getProperty(key):根据键获取值

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

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

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

//Properties读文件
public class Properties02 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        //加载指定的配置文件
        properties.load(new FileReader("src\\mysql.properties"));
        //把键值对k-v显示到控制台
        properties.list(System.out);
        //根据key 获取对应的值
        properties.getProperty("user");
        properties.getProperty("pwd");
    }
}
//Properties创建、修改配置文件
public class Properties03 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        //创建
        //如果该文件没有key,就是创建
        //如果该文件有key,就是修改
        properties.setProperty("charset","utf8");
        properties.setProperty("user","汤姆");//注意保存时,是中文的unicode码
        properties.setProperty("pwd","1111");
        //将k-v存储到文件中即可
        properties.store(new FileOutputStream("src\\mysql2.properties"),null);
        System.out.println("保存配置文件成功");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值