第十四话-JavaIO框架

2022/4/23 11:42:34

本文主要是介绍第十四话-JavaIO框架,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

分类:

  • 按单位:

    • 字节流:以字节为单位,可以读写所有数据
    • 字符流:以字符为单位,只能读写文本数据
  • 按功能:

    • 节点流:具有实际传输数据的读写功能。
    • 过滤流:在节点流的基础之上增强功能

字节流:

字节流的父类(抽象类):

  • InputStream:字节输入流
    • FileInputStream:public int read(byte[] b)//从流中读取多个字节,将读到内容存入b数组,返回实际读到的字节数;如果达到文件的尾部,则返回-1。
  • OutputStream:字节输出流
    • FileOutputStream:public void write(byte[] b)//一次写多个字节,将b数组中的所有字节,写入输出流。

字节流

FileInputStream类

package com.xie.io;

import java.io.FileInputStream;

public class Demo01 {
    public static void main(String[] args) throws Exception {
        //1.创建FileInputStream,并指定文件路径
        FileInputStream fis = new FileInputStream("D:\\java基础\\测试文件\\FileInputStream.txt");
        //2.读取文件,单个字节读取
//        int data = 0;
//        while((data=fis.read())!=-1){
//            System.out.println((char)data);
//        }
        //定义一次读取长度
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count=fis.read(buf))!=-1){
            System.out.println(count);
            System.out.println(new String(buf,0,count));
        }
        fis.close();
        System.out.println("执行结束");
    }
}

FileOutputStream类

package com.xie.io;

import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

public class Demo02 {
    public static void main(String[] args) throws Exception {
        //FileOutputStream构造方法第二个参数为true,则增量输出,不会覆盖原来的内容
        FileOutputStream fos = new FileOutputStream("D:\\java基础\\测试文件\\FileOuputStream.txt",true);
        //单个字符输出
//        fos.write(97);
//        fos.write('b');
//        fos.write('c');
        String str = "Hello World!";
        fos.write(str.getBytes());
        fos.close();
        System.out.println("执行完毕1");
    }
}

字节流复制文件

package com.xie.io;

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

public class Demo03 {
    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("D:\\test.png");
        FileOutputStream fos = new FileOutputStream("D:\\test2.png");
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count=fis.read(buf))!=-1){
            fos.write(buf,0,count);
        }
        fis.close();
        fos.close();
        System.out.println("执行完毕");
    }
}

缓冲流

BufferedInputStream/BufferedOutputStream

  • 提高IO效率,减少访问磁盘的次数
  • 数据存储在缓冲区中,flush是将缓存区的内容写入文件中,也可以直接close

BufferedInputStream代码:

package com.xie.io;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

public class Demo04 {
    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("D:\\FileInputStream.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
//        int data = 0;
//        while ((data=bis.read())!=-1){
//            System.out.println((char)data);
//        }
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count=bis.read(buf))!=-1){
            System.out.println(new String(buf,0,count));
        }
        bis.close();
    }
}

BufferedOutputStream代码:

package com.xie.io;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

public class Demo05 {
    public static void main(String[] args) throws Exception {
        FileOutputStream fos = new FileOutputStream("D:\\buffer.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        for (int i = 0; i < 10; i++) {
            bos.write("helloWorld!\r\n".getBytes());
            bos.flush();//刷新到硬盘
        }
        //关闭(会内部调用flush方法)
        bos.close();
    }
}

对象流

ObjectInputStream/ObjectOutputStream

  • 增强了缓冲区功能
  • 增强了读写8种基本数据类型和字符串功能
  • 增强了读写对象的功能:readObject()从流中读取一个对象

​ writeObject(Objcet obj)向流中写入一个对象

  • 使用流传输对象的过程称为序列化(将对象写到硬盘)、反序列化(从硬盘读到内存)。

序列化-ObjectOutputStream

package com.xie.io;

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

public class Demo06 {
    public static void main(String[] args) throws Exception {
        FileOutputStream fos = new FileOutputStream("D:\\stu.bin");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        //Student必须实现Serializable接口,作为标记可以序列化
        Student stu1 = new Student("ZHANGSAN",33);
        oos.writeObject(stu1);
        oos.close();
        System.out.println("执行完毕");
    }
}
package com.xie.io;

import java.io.Serializable;

public class Student implements Serializable {
    private String name;
    private int age;

    public Student(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;
    }

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

反序列化-ObjectInputStream

package com.xie.io;

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

public class Demo07 {
    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("D:\\stu.bin");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Student s = (Student)ois.readObject();
        ois.close();
        System.out.println("执行完毕");
        System.out.println(s.toString());
    }
}

注意事项:

  • 序列化类必须实现Serializable接口
  • 序列化类中对象属性要求实现Serializable接口
  • 序列化版本号ID,保证序列化的类和反序列化的类是同一个类
private static final long serialVersionUID = 100L;
  • 使用transient(瞬间的)修饰属性,这个属性不能序列化
  • 静态属性不能序列化
  • 可以序列化多个对象,通过集合实现

字符流

字符编码

  • ISO-8859-1 收录除ASCII 外,还包括西欧等对应的文字符号
  • UTF-8 针对Unicode码表的可变长度字符编码,一个汉字3个字节
  • GB2312 简体中文
  • GBK 简体中文,扩充
  • BIG5 台湾,繁体中文

编码与解码方式不一致,会出现乱码

字符流抽象类

字节流读取汉字,按照字节读取并解析,但是一个汉字三个字节,解析乱码

Reader:字符输入流

  • public int read(){}
  • public int read(char[] c){}
  • public int read(char[] b,int off,int len){}

Writer:字符输出流

  • public void write(int n){}
  • public void write(String str){}
  • public void write(char[] c){}

FileReader

package com.xie.io;

import java.io.FileReader;

public class Demo08 {
    public static void main(String[] args) throws Exception{
        FileReader fr = new FileReader("D:\\buffer.txt");
        int data = 0;
        while ((data = fr.read()) != -1){//读取一个字符
            System.out.print((char)data);
        }
        fr.close();
        System.out.println("----------------");
        FileReader fr2 = new FileReader("D:\\buffer.txt");
        int count = 0;
        char[] buf =new char[3];
        while ((count = fr2.read(buf)) != -1){//读取buf的长度,赋值给buf,位置赋值给count
            System.out.println(new String(buf,0,count));
        }
        fr2.close();
    }
}

FileReader

package com.xie.io;

import java.io.FileWriter;

public class Demo09 {
    public static void main(String[] args) throws Exception {
        FileWriter fr = new FileWriter("D:\\buffer.txt");
        for (int i = 0; i < 10; i++) {
            fr.write("java是好语言\r\n");
            fr.flush();
        }
        fr.close();
        System.out.println("执行完毕");
    }
}

字符流复制

package com.xie.io;

import java.io.FileReader;
import java.io.FileWriter;

public class Demo10 {
    public static void main(String[] args) throws Exception{
        //字符流实现文件复制,只能复制文本文件
        FileReader fr = new FileReader("D:\\buffer.txt");
        FileWriter fw = new FileWriter("D:\\buffer2.txt");
        int data = 0;
        while ((data = fr.read()) != -1){
            fw.write(data);
            fw.flush();
        }
        fr.close();
        fw.close();
        System.out.println("执行完毕");
    }
}

字符缓冲流

BufferedReader/BufferedWriter

  • 高校读写
  • 支持输入换行符
  • 可一次读写一行

BufferedReader

package com.xie.io;

import com.xie.oop.demo03.B;

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

public class Demo11 {
    public static void main(String[] args) throws Exception{
        FileReader fr = new FileReader("D:\\buffer.txt");
        BufferedReader br = new BufferedReader(fr);
        char[] buf = new char[1024];
        int count = 0;
        while ((count = br.read(buf)) != -1){
            System.out.println(new String(buf,0,count));
        }
        br.close();
        System.out.println("--------");
        FileReader fr2 = new FileReader("D:\\buffer.txt");
        BufferedReader br2 = new BufferedReader(fr2);
        String line = null;
        while ((line=br2.readLine()) != null){
            System.out.println(line);
        }
        br2.close();
    }
}

BufferedWriter

package com.xie.io;

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

public class Demo12 {
    public static void main(String[] args) throws Exception{
        FileWriter fw = new FileWriter("D:\\buffer.txt");
        BufferedWriter bw = new BufferedWriter(fw);
        for (int i = 0; i < 10; i++) {
            bw.write("好好学习");
            bw.newLine();
            bw.flush();
        }
        bw.close();
        System.out.println("执行完毕");
    }
}

PrintWriter

  • 封装了print()、println()方法,支持写入后换行。

  • 支持数据原样打印

package com.xie.io;

import java.io.PrintWriter;

public class Demo13 {
    public static void main(String[] args) throws Exception{
        PrintWriter pw = new PrintWriter("D:\\buffer.txt");
        pw.println(97);
        pw.println(true);
        pw.println(3.14);
        pw.println('a');
        pw.close();
        System.out.println("执行完毕");
    }
}

转换流

  • 桥转换流:InputStreamReader/OutputStreamWriter
    • 可将字节流转换为字符流
    • 可设置字符的编码方式
package com.xie.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Demo14 {
    public static void main(String[] args) throws Exception{
        FileInputStream fi = new FileInputStream("D:\\buffer2.txt");
        InputStreamReader isr = new InputStreamReader(fi,"utf-8");
        int data = 0;
        while ((data = isr.read()) != -1) {
            System.out.print((char)data);
        }
        isr.close();
        System.out.println("------------------");
        FileOutputStream fo = new FileOutputStream("D:\\buffer.txt");
        OutputStreamWriter osw = new OutputStreamWriter(fo,"gbk");
        for (int i = 0; i < 5; i++) {
            osw.write("niho你好\r\n");
            osw.flush();
        }
        osw.close();
        System.out.println("执行完毕");
    }
}

File类

文件、文件夹操作

package com.xie.io;

import java.io.File;
import java.util.Date;

public class Demo15 {
    public static void main(String[] args)  throws Exception{
        //separator();
        //fileOpe();
        dirOpe();
    }
    //分隔符
    public static void separator(){
        System.out.println("路径分隔符" + File.pathSeparator);
        System.out.println("名称分隔符" + File.separator);
    }
    //文件操作
    public static void fileOpe() throws Exception{
        //1.创建文件
        File file = new File("D:\\buffer.txt");
        //System.out.println(file.toString());
        if(!file.exists()){
            boolean b = file.createNewFile();
            System.out.println("创建结果:" + b);
        }
        //2.1删除文件
        //System.out.println("删除结果:" + file.delete());
        //2.2使用jvm退出时删除
//        file.deleteOnExit();
//        Thread.sleep(5000);
        //3获取文件信息
        System.out.println("获取文件的绝对路径" + file.getAbsolutePath());
        System.out.println("获取路径" + file.getPath());
        System.out.println("获取文件名称" + file.getName());
        System.out.println("获取文件长度" + file.length());
        System.out.println("获取文件父目录" + file.getParent());
        System.out.println("文件创建时间" + new Date(file.lastModified()).toLocaleString());
        //4判断
        System.out.println("是否可写:" + file.canWrite());
        System.out.println("是否是文件" + file.isFile());
        System.out.println("是否隐藏" + file.isHidden());
    }

    //文件夹操作
    public static void dirOpe() throws Exception{
        //1.创建文件夹
        File dir = new File("D:\\aaa\\bbb\\ccc");
        System.out.println(dir.toString());
        if(!dir.exists()){
            //dir.mkdir();//只能创建单级目录
            System.out.println("创建结果:" + dir.mkdirs());//创建多级目录

        }
        //2.删除文件夹,注:只能删除单个文件夹。只能删除空文件夹
        //System.out.println("删除结果:" + dir.delete());//直接删除
        //dir.deleteOnExit();//使用jvm删除
        //Thread.sleep(5000);
        //3.获取文件夹信息
        System.out.println("获取绝对路径:" + dir.getAbsolutePath());
        System.out.println("获取路径:" + dir.getPath());
        System.out.println("获取文件夹名称:" + dir.getName());
        System.out.println("获取父目录:" + dir.getParent());
        System.out.println("获取创建时间:" + new Date(dir.lastModified()).toLocaleString());
        //4.判断
        System.out.println("是否是文件夹:" + dir.isDirectory());
        System.out.println("是否隐藏" + dir.isHidden());
        //5.遍历文件夹
        File dir2 = new File("D:\\apache-tomcat-9.0");
        String[] files = dir2.list();
        for (String file : files) {
            System.out.println(file);
        }
    }
}

FileFilter接口

  • public interface FileFilter

    • boolean accept (File pathname)
  • 当调用File类中的listFiles()方法时,支持传入FileFilter接口实现类,对获取文件进行过滤,只有满足条件的文件才可出现在listFiles()的返回值中。

package com.xie.io;

import java.io.File;
import java.io.FileFilter;

public class Demo16 {
    public static void main(String[] args) {
        File dir2 = new File("D:\\apache-tomcat-9.0");
        File[] files =  dir2.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if(pathname.getName().endsWith(".txt")){
                    return true;
                }
                return false;
            }
        });
        for (File file : files) {
            System.out.println(file.getName());
        }
    }
}

递归遍历、删除

package com.xie.io;

import java.io.File;

public class Demo17 {
    public static void main(String[] args) {
        listDir(new File("D:\\BaiduNetdiskDownload"));
        deleteDir(new File("D:\\aaa"));
    }
    //遍历文件夹
    public static void listDir(File dir){
        File[] files = dir.listFiles();
        System.out.println(dir.getAbsolutePath());
        if(files != null && files.length> 0 ){
            for (File file : files) {
                if(file.isDirectory()){
                    listDir(file);
                }else {
                    System.out.println(file.getAbsolutePath());
                }
            }
        }
    }
    //遍历删除文件夹
    public static void deleteDir(File dir){
        File[] files = dir.listFiles();
        if(files != null && files.length> 0 ){
            for (File file : files) {
                if(file.isDirectory()){
                    deleteDir(file);
                }else {
                    System.out.println(file.getAbsolutePath()+"--删除:"+file.delete());
                }
            }
        }
        System.out.println(dir.getAbsolutePath()+"删除:"+dir.delete());
    }
}

Properties

  • Properties:属性集合

  • 特点:

    1. 存储属性名和属性值
    2. 属性名和属性值都是字符串类型
    3. 没有泛型
    4. 和流有关
package com.xie.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.Set;

public class Demo18 {
    public static void main(String[] args) throws Exception{
        Properties properties = new Properties();
        properties.setProperty("username","zhangsan");
        properties.setProperty("age","33");
        System.out.println(properties);
        //遍历
        //1.keySet遍历
        //2.entrySet遍历
        //3.stringPropertyNames()遍历
        Set<String> pronames = properties.stringPropertyNames();
        for (String proname : pronames) {
            System.out.println(proname+"----"+properties.getProperty(proname));
        }
        //和流有关的方法
        //1. list()打印
        PrintWriter pw = new PrintWriter("d:\\print.txt");
        properties.list(pw);
        pw.close();
        //2. store()保存
        FileOutputStream fos = new FileOutputStream("d:\\store.properties");
        properties.store(fos,"zhushi");
        fos.close();
        //3. load()加载
        Properties properties1 = new Properties();
        FileInputStream fis = new FileInputStream("d:\\store.properties");
        properties1.load(fis);
        fis.close();
        System.out.println(properties1);
    }
}


这篇关于第十四话-JavaIO框架的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程