IO流

文件

  • :数据在数据源(文件)和程序(内存)之间经历的路径
  • 输入流:数据从数据源(文件)到程序(内存)的路径
  • 输出流:数据从程序(内存)到数据源(文件)的路径

创建文件

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

  • new File(File parent, String child) // 根据父目录文件 + 子路径构建

  • new File(String parent, String child) // 根据父目录 + 子目录构建

createNewFile // 创建新文件

@Test
    public void Create01() {
        String filePath = "e:\\news1.txt";
        File file = new File(filePath);
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void Create02() {
        File parentfile = new File("e:\\");
        String filename = "new2.txt";
        File file = new File(parentfile, filename);

        try {
            file.createNewFile();
            System.out.println("创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void Create03() {
        String parentPath = "e:\\";
        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

 // 获取文件信息
    @Test
    public void info() {
        // 先创建文件对象
        File file = new File("e:\\news1.txt");

        System.out.println("文件名字" + file.getName());
        System.out.println("文件绝对路径" + file.getAbsolutePath());
        System.out.println("文件父级目录" + file.getParent());
        System.out.println("文件大小(字节) " + file.length());
        System.out.println("文件是否存在 " + file.exists());
        System.out.println("是不是一个文件 " + file.isFile());
        System.out.println("是不是一个目录 " + file.isDirectory());

    }

目录操作

mkdir 创建一级目录 mkdirs 创建多级目录 delete 删除空目录或者文件

 @Test
    public void del() {
        String directionPath = "e:\\a\\b\\c";
        File file = new File(directionPath);
        if (file.exists()) {
            if (file.exists()) {
                System.out.println(directionPath + "删除成功");
            }else {
                System.out.println(directionPath + "删除失败");
            }
        }else {
            System.out.println("目录不存在");
            if (file.mkdirs()) {
                System.out.println("创建成功");
            } else {
                System.out.println("创建失败");
            }
        }
    }

javaIO流原理及流的分类

I/O : Input/Output

字节流(8 bit) 二进制文件, 字符流 文本文件 输入流,输出流 节点流,处理流/包装流

字节流 : 输入流: InputStream 输出流: OutputStream 字符流 : 输入流 : Reader 输出流: Writer 都是 抽象类

字节输入流

1.FileInputStream 文件输入流 2.BufferrfInputStream 缓冲字节输入流 3.ObjectInputStream 对象字节输入流

一.

    @Test
    public void readFile01() {
        String filePath = "e:\\news1.txt";
        int read = 0;
        FileInputStream file = null;
        try {
            // 创建FileInputStream 读取文件
            file = new FileInputStream(filePath);

            while ((read = file.read()) != -1){
                System.out.print((char) read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭文件,释放资源
            try {
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Test
    public void readFile02() {
        String filePath = "e:\\news1.txt";
        int readLen = 0;
        byte[] buf = new byte[8];
        FileInputStream file = null;
        try {
            // 创建FileInputStream 读取文件
            file = new FileInputStream(filePath);
            // 返回实际读取的字节数
            while ((readLen = file.read(buf)) != -1){
                System.out.print(new String(buf, 0 , readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭文件,释放资源
            try {
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

二.FileOutputStream

    @Test
    // 使用FileOutputStream将数据写入文件中
    // 如果文件不存在则创建文件
    public void writeFile() {
        // 创建 FileOutputStream 对象
        String filePath = "e:\\a.txt";
        FileOutputStream fileOutputStream = null;
        try {
            // 得到FileOutputStream 对象
            // fileOutputStream = new FileOutputStream(filePath); 写入内容会覆盖原来
            // fileOutputStream = new FileOutputStream(filePath , true); 写入当前内容,追加到文件后面
            fileOutputStream = new FileOutputStream(filePath , true);

            // 1.写入一个字节
//            fileOutputStream.write('H');

            String str = "Hello , world";

//            // str.getBytes() 可以把字符串 --> 字节数组
            // 2.
//            fileOutputStream.write(str.getBytes(StandardCharsets.UTF_8));

            //3.
            fileOutputStream.write(str.getBytes(StandardCharsets.UTF_8), 0 , str.length());

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

文件拷贝

1.创建文件的输入流,将程序读入到程序 2.创建文件的输出流,将读到的文件数据,写入指定文件

public class FileCopy {
    public static void main(String[] args) {
        String file = "e:\\news1.txt";
        String endPath = "d:\\news1.txt";
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {

            fileInputStream = new FileInputStream(file);
            fileOutputStream = new FileOutputStream(endPath);

            byte[] buf = new byte[1024];
            int readLen = 0;
            while ((readLen = fileInputStream.read(buf)) != -1) {

                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

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

        String filePath = "e:\\new2.txt";
        FileReader fileReader = null;
        int data = 0;
        // 1.创建FileReader对象
        try {
            fileReader = new FileReader(filePath);
            // 单个字符读取
            while ((data = fileReader.read()) != -1) {
                System.out.print((char) data);
            }

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

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

    @Test
    // 字符数组读取文件
    public void Filereader() {

        String filePath = "e:\\new2.txt";
        FileReader fileReader = null;

        int readLen = 0;
        char[] buf = new char[8];

        // 1.创建FileReader对象
        try {
            fileReader = new FileReader(filePath);

            while ((readLen = fileReader.read(buf)) != -1) {
                System.out.print(new String(buf, 0, readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

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

        }
    }
}

四.FileWriter

FileWriter使用后,必须close或flush,否则写入不到指定文件



import java.io.IOException;

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

        String filePath = "e:\\news3.txt";

        java.io.FileWriter fileWriter = null;

        char[] chars = {'a' , 'b', 'c'};
        try {

            // 默认覆盖模式,无true
            fileWriter = new java.io.FileWriter(filePath);

            fileWriter.write('h');

            fileWriter.write(chars);

            fileWriter.write("王志浩".toCharArray(), 0, 2);

            fileWriter.write("hello,world");

            fileWriter.write("北京伤害",0,2);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // ==FileWriter==使用后,必须close或flush,否则写入不到指定文件

            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("程序结束~~");
    }
}

节点流和处理流

1.节点流是可以从一个特点的数据源读写数据,如FileReader,FileWriter

2.处理流是"连接"在已存在的流之上,为程序提供更为强大的读写功能,如BufferedReader,BufferedWriter

BufferedReader 和 BufferedWriter

处理流,字符流

关闭处理流,只需关闭外层流就可

按照字符读取操作,不要去操作二进制文件,可能造成文件损坏 二进制文件[声音,视频,doc,pdf]



import org.junit.Test;

import java.io.*;
import java.io.FileWriter;

public class BufferedReaderDemo {
    public static void main(String[] args) throws IOException {

        String filePath = "e:\\new2.txt";
        // 创建bufferedReader
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
        // 读取bufferedReader
        String line;
        // 按行读取,返回为空时读取完毕
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }

        // 关闭流只需要关闭BufferedReader,底层会自动关闭节点流
        bufferedReader.close();
    }

    @Test
    public void bufferedwriter() throws IOException {
        String filePath = "e:\\news1.txt";

        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath,true));
        bufferedWriter.write("hello,world");
        // 插入一个和系统相关的换行符
        bufferedWriter.newLine();
        bufferedWriter.write("hello1,world");
        bufferedWriter.write("hello2,world");

        bufferedWriter.close();

    }

    @Test
    public void BufferedCopy(){

        String srcFilePath = "e:\\news1.txt";
        String destFilePath = "d:\\test.txt";

        BufferedReader br = null;
        BufferedWriter bw = null;

        String line;

        try {

            br = new BufferedReader(new FileReader(srcFilePath));
            bw = new BufferedWriter(new FileWriter(destFilePath));

            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }
            System.out.println("拷贝完毕");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}



BufferedInputStream 和 BufferedOutputStream

字节流和处理流

字节流可以操作二进制文件,也可以操作文本文件

package com.wzh.IO流学习;

import java.io.*;

public class ObjectOutStream_ {
    public static void main(String[] args) throws IOException {
        // 完成数据的序列化
        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
        oos.writeChar('a');
        oos.writeDouble(9.5);
        oos.writeUTF("wzh"); // String

        oos.writeObject(new dog("旺财", 10));

        oos.close();
        System.out.println("数据保存完毕(序列化形式)");
    }
}

// 如果需要序列化某个类的对象,实现Serializable
class dog implements Serializable {
    private String name;
    private int age;
    private static final long serialVersionUID = 1L;

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

    public dog() {
    }

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

package com.wzh.IO流学习;

import java.io.*;

public class ObjeactInputStream_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException {

        String filePath = "e:\\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());
        Object o = ois.readObject();
        System.out.println("运行类型" + o.getClass());
        System.out.println(o);
        // 关闭流
        ois.close();
        // 调用dog方法,需要向下转型
        // 将dog的定义,拷贝到其他可以引用的地方
        dog dog2 = (dog)o;
        System.out.println(dog2.getName() + dog2.getAge());
    }
}

//// 如果需要序列化某个类的对象,实现Serializable
//class dog implements Serializable {
//    private String name;
//    private int age;
//
//    public dog(String name, int age) {
//        this.name = name;
//        this.age = age;
//    }
//
//    public dog() {
//    }
//
//    @Override
//    public String toString() {
//        return "dog{" +
//                "name='" + name + '\'' +
//                ", age=" + age +
//                '}';
//    }
//}

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

标准输入输出流

System.in System.out

转化流

字节流转化成字符流

package com.wzh.IO流学习;

import java.io.*;

public class Demo01 {
    public static void main(String[] args) throws IOException {
        // 将字节流FileInputStream 转成字符流 InputStreamReader,指定编码
        String filePath = "e:\\news1.txt";
        InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");

        // new FileInputStream(filePath) 转成 InputStreamReader

        // 把InputStreamReader 传入 BufferedReader
        BufferedReader br = new BufferedReader(isr);

//        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "gbk"));

        String s = br.readLine();
        System.out.println("读取内容=" + s);

        br.close();
    }
}

package com.wzh.IO流学习;

import java.io.*;

public class Demo02 {
    public static void main(String[] args) throws IOException {

        // 把 FileOutputStream 字节流 转化成 OutoutStreamWriter 字符流
        // 指定gbk
        String filePath = "e:\\wzh.txt";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), "gbk");
        osw.write("hello,world");

        osw.close();
        System.out.println("succeed");
    }

}

打印流 PrintStream , PrintWriter

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

package com.wzh.IO流学习;

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

public class Demo02 {
    public static void main(String[] args) throws IOException {
        PrintStream out = System.out;
        out.print("john,hello");
        // 字节打印流
        // 在默认情况下,PrintStream 输出数据的位置是 标准输出 ,即显示器
        out.write("你好,helloworld".getBytes(StandardCharsets.UTF_8));
        out.close();

        // 修改打印流的位置 \ 设备
        // 输出到 e:\\a.txt
        System.setOut(new PrintStream("e:\\a.txt"));
        System.out.println("hello,world1111");
    }
}


package com.wzh.IO流学习;

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

public class demo03 {
    public static void main(String[] args) throws IOException {

        // 字符打印流
//        PrintWriter printWriter = new PrintWriter(System.out);
        PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\b.txt"));
        printWriter.println("hello, world 2222");
        printWriter.close();
    }
}

Properties类

专门用于读写配置文件的集合类 配置文件的格式: 键=值 键=值

键值对不需要有空格,值不需要用引号一起来,默认类型是String

package com.wzh.IO流学习;

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

public class Demo04 {
    public static void main(String[] args) throws IOException {

        // 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");
        System.out.println("用户名是 " + user);

    }
}

package com.wzh.IO流学习;

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

public class Demo05 {
    public static void main(String[] args) throws IOException {
        // 使用Properties 类来创建配置文件,修改配置文件内容

        Properties properties = new Properties();
        // 创建
        properties.setProperty("charset", "utf-8");
        properties.setProperty("user", "Tom");
        properties.setProperty("pwd", "123456");

        // 将k-v存储到文件中
        properties.store(new FileOutputStream("src\\mysql2.proerties"),null);
        System.out.println("succeed");

        // 如果该文件没有key,就是创建
        // 如果文件有key,就是修改
    }
}


本文章使用limfx的vscode插件快速发布