Java之IO流使用

输入输出流四个抽象类

字节流 字符流
输入流 InputStream Reader
输出流 OutputStream Writer

一个字符两个字节(byte),一个字节八位(bit)

Reader:用于读取字符流的抽象类。 子类必须实现的唯一方法是read(char [],int,int)和close()

Writer:用于写入字符流的抽象类。 子类必须实现的唯一方法是write(char [],int,int),flush()和close()

InputStream:表示输入字节流的所有类的超类

OutputStream:表示字节输出流的所有类的超类

字节流

使用字节流对文件进行读写

private static void printFile(File file) {
    FileInputStream inputStream = null;
    try {
        inputStream = new FileInputStream(file);
        //每次读取1024个字节
        byte[] buffer = new byte[1024];
        //len为字节数组中存储的字节数
        int len;
        while ((len = inputStream.read(buffer)) > 0) {
            System.out.println(new String(buffer, 0, len));
        }
        inputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭流
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用字节流对文件进行复制

private static void copyFile(File file, File copy) {
    FileOutputStream outputStream = null;
    FileInputStream inputStream = null;
    try {
        outputStream = new FileOutputStream(copy);
        inputStream = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

字符流

使用字符流读取文件

private static void charFlow(File file) {
    try {
        FileReader fr = new FileReader(file);
        char[] c = new char[1024];
        int len = 0;
        while ((len = fr.read(c)) != -1) {
            System.out.println(new String(c, 0, len));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

编码与解码

编码:把字符串变成字节数组(String→byte[]),代表方法为str.getBytes(charsetName)
解码:把字节数组变成字符串(byte[]→String),代表方法为new String(byte[], charsetName)

猜你喜欢

转载自blog.csdn.net/Ca_CO3/article/details/81433233