IO中的一些常用流

字节输入流FileInputStream

package IO;

import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author 小小小白白白白
 */
public class Operate {

    @Test
    public void readFile1(){
        String Filepath = "e:\\hello.txt";
        //临时存储文件中的单个字节
        int readDate;
        FileInputStream fis = null;
        try {
            //创建FileInputStream对象用于读取文件
            fis = new FileInputStream(Filepath);
            //该输入流读取一个字节的数据(这种方式不适合读取汉字),赋给readDate
            //循环输出直到文件最后遇到-1时停止
            while((readDate=fis.read()) != -1){
                //转换成char型输出
                System.out.print((char)readDate);
            }
            //将IO的所有异常捕获
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //当文件流用完后,一定要关闭,避免占用资源
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Test
    public void readFile2(){
        String Filepath = "e:\\hello.txt";
        //字节数组用于一次存储多个字节
        byte[] bytes = new byte[8];
        //确定数组的长度
        int length;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(Filepath);
            while((length=fis.read(bytes)) != -1){
                //转换成字符串输出,一次输出8个
                System.out.print(new String(bytes,0,length));
            }
            //将IO的所有异常捕获
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //当文件流用完后,一定要关闭,避免占用资源
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

字节输出流FileOutputStream

package IO;

import org.junit.jupiter.api.Test;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author 小小小白白白白
 */
public class Write {

    @Test
    public void write(){
        String Filepath="e:\\hello.txt";
        FileOutputStream fio=null;
        try {
            //FileOutputStream的默认写入方式是覆盖
            //FileOutputStream(Filepath,true)后面跟个true就会改变写入方式,变为附加到文件末尾
            fio=new FileOutputStream(Filepath,true);
            //对指定的文件写入一个W,如果该文件不存在就会创建一个
            fio.write('W');

            //写入一个字符串
            String str="qwert";
            //因为write接收的内容是一个字符数组
            //getBytes可以将字符串转成字符数组
            fio.write(str.getBytes());

            //写入指定长度的字符串
            fio.write(str.getBytes(),0,4);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

实现文件拷贝

package IO;

import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author 小小小白白白白
 */
public class Filecopy {

    @Test
    public void copy(){
        String Filepath="f:\\Re.png";
        String Filepath1="e:\\Re.png";
        FileInputStream fis = null;
        FileOutputStream fio=null;
        //每次读取1M
        byte[] buffer = new byte[1024];
        int len = 0;
        try {
            fis=new FileInputStream(Filepath);
            fio=new FileOutputStream(Filepath1);
            while((len = fis.read(buffer))!=-1){
                //使用该方法防止文件损坏
                fio.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                fio.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

处理流(包装流)BufferedReader和BufferedWriter

package IO;

import org.junit.jupiter.api.Test;
import java.io.*;

/**
 * @author 小小小白白白白
 */
public class Buffer {


    /**
     * BufferedReader
     */
    @Test
    public void buffer() throws Exception {
        String filepath ="e:\\hello.txt";
        BufferedReader br = new BufferedReader(new FileReader(filepath));
        String line;
        //按行读取
        while ((line =br.readLine())!=null) {
            System.out.println(line);
        }
        //关闭包装流,它会自动关闭节点流
        br.close();
    }


    /**
     * BufferedWriter
     */
    @Test
    public void buffer1() throws Exception {
        String filepath ="e:\\hello.txt";
        BufferedWriter bw = new BufferedWriter(new FileWriter(filepath,true));
        //插入一个换行
        bw.newLine();
        bw.write("123");
        bw.write("456");
        bw.write("789");
        //关闭包装流,它会自动关闭节点流
        bw.close();
    }


    /**
     * 文件拷贝
     * 不要去拷贝二进制文件
     */
    @Test
    public void buffer2() throws Exception{
        String filepath ="f:\\Re.txt";
        String filepath1 ="e:\\Re.txt";
        BufferedReader br = new BufferedReader(new FileReader(filepath));
        BufferedWriter bw = new BufferedWriter(new FileWriter(filepath1));
        String line = null;
        while ((line = br.readLine()) != null) {
            bw.write(line);
        }
        br.close();
        bw.close();
    }
}

BufferedInputStream和BufferedOutputStream

package IO;

import org.junit.jupiter.api.Test;
import java.io.*;

/**
 * @author 小小小白白白白
 */
public class Buffered {

    @Test
    public void buffered() throws Exception{
        String filepath = "f:\\Re.png";
        String filepath1 = "e:\\Re.png";
        BufferedInputStream bi = new BufferedInputStream(new FileInputStream(filepath));
        BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(filepath1));
        byte[] buffer = new byte[1024];
        int len;
        while((len=bi.read(buffer))!=-1){
            bo.write(buffer, 0, len);
        }
        bi.close();
        bo.close();
    }
}

对象流ObjectOutputStream和ObjectInputStream

package IO;

import org.junit.jupiter.api.Test;
import java.io.*;

/**
 * @author 小小小白白白白
 */
public class Oos {

    /**
     * 序列化保存
     */
    @Test
    public void ObjectOutputStream() throws Exception {
        //它序列化后保存的不是文本的格式,而是它自己的格式
        String filepath ="e:\\hello.dat";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filepath));
        oos.writeInt(100);
        oos.writeUTF("你好吗");
        oos.writeBoolean(false);
        //如果要保存一个类,那么该类需要实现Serializable接口
        oos.writeObject(new Dog("小黄",2));

        oos.close();
    }


    /**
     * 序列化恢复
     */
    @Test
    public void ObjectInputStream() throws Exception {
        //恢复的顺序要和保存的顺序一致
        String filepath ="e:\\hello.dat";
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filepath));
        System.out.println(ois.readInt());
        System.out.println(ois.readUTF());
        System.out.println(ois.readBoolean());
        Object dog = ois.readObject();
        System.out.println(dog);

        //如果要使用Dog中的方法需要向下转型(要在同一包内并且该类要位于能够引用到的位置)
        //如果在不同的包下需要将该类设为public
        Dog dog1=(Dog)dog;
        System.out.println(dog1.toString());

        ois.close();
    }
}

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

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

    /**
     * 如果之前序列化生成的时候没有toString方法
     * 恢复的时候会报错
     */
    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

转换流InputStreamReader和OutputStreamWriter

public class Input {
    public static void main(String[] args) throws IOException {
        String filepath="e:\\hello.txt";
        //把FileInputStream转成InputStreamReader,并指定其编码格式
        InputStreamReader isr = new InputStreamReader(new FileInputStream(filepath),"gbk");
        //把InputStreamReader传入BufferedReader
        BufferedReader br = new BufferedReader(isr);
        //将第一行的内容存入s并输出
        String s = br.readLine();
        System.out.println(s);
        br.close();
    }

    @Test
    public void Output() throws IOException {
        String filepath="e:\\hello.txt";
        String charset="gbk";
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filepath),charset);
        osw.write("梅长苏");
        osw.close();
    }

打印流PrintStream和PrintWriter

/**
     * 打印流PrintStream
     */
    @Test
    public void Print() throws IOException {
        PrintStream out = System.out;
        //PrintStream的默认打印位置是显示器
        out.println("识遍天下英雄路,");
        //因为PrintStream的底层使用的是write,所以我们可以调用write进行打印输出
        out.write("俯首江左有梅郎。".getBytes());
        //修改打印的位置
        System.setOut(new PrintStream("e:\\hello.txt"));
        System.out.println("识遍天下英雄路,俯首江左有梅郎。");
        out.close();
    }

    /**
     * 打印流PrintWriter
     */
    @Test
    public void PrintW() throws IOException {
        PrintWriter pw = new PrintWriter(new FileWriter("e:\\hello.txt"));
        pw.println("披衣时,又是一年,梅岭雪落。");
        //只有执行完close后文件才会刷新
        pw.close();

    }

上一篇:Python:文件读写


下一篇:CSS实现关闭叉叉按钮