Java学习路线-26:字节流与字符流OutputStream/InputStream/Writer/Reader

简介: Java学习路线-26:字节流与字符流OutputStream/InputStream/Writer/Reader

第16章 字节流与字符流

72 流的基本概念

File类是唯一一个与文件本身有关的程序处理类

File类只能够操作文件本身,而不能操作文件内容


IO操作:输入输出操作


java.io 抽象类


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

文件处理流程:

1、File找到一个文件

2、通过字节流或字符流的子类为父类对象实例化

3、利用字节流或字符流中的方法实现数据出入与输出操作

4、流的操作属于资源操作,资源操作必须进行关闭


73 OutputStream字节输出流

实现代码


public interface AutoCloseable {
    void close() throws Exception;
}
public interface Closeable extends AutoCloseable {
    public void close() throws IOException;
}
public interface Flushable {
    void flush() throws IOException;
}
public abstract class OutputStream 
    implements Closeable, Flushable{
    public abstract void write(int b) throws IOException;
    public void write(byte b[]) throws IOException;
    public void write(byte b[], int off, int len) throws IOException;
}
// 子类
public class FileOutputStream extends OutputStream{
    // 覆盖
    public FileOutputStream(File file) throws FileNotFoundException
    // 追加
    public FileOutputStream(File file, boolean append) 
        throws FileNotFoundException;
}

内容输出到文件


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
class Demo{
    public static void main(String[] args) throws IOException {
        File file = new File("demo/demo.txt");
        // 父级目录不存在则创建
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdir();
        }
        String message = "这是输出的内容";
        // 将字符串转换为字节数组输出到文件,并关闭文件
        FileOutputStream output = new FileOutputStream(file);
        output.write(message.getBytes());
        output.close();
    }
}

自动关闭的写法


try(FileOutputStream output = new FileOutputStream(file)){
    output.write(message.getBytes());
}catch (IOException e){
    e.printStackTrace();
}

使用追加换行输出


String message = "这是输出的内容\r\n";
FileOutputStream output = new FileOutputStream(file, true);
output.write(message.getBytes());
output.close();

74 InputStream字节输入流

public abstract class InputStream implements Closeable{
    // 读取单个字节数据,读到文件底部返回-1
    public abstract int read() throws IOException;
    // 读取一组字节数据,返回读取的个数,文件底部返回-1
    public int read(byte b[]) throws IOException;
    public int read(byte b[], int off, int len) throws IOException;
}

文件尾部返回 -1, 表示文件读取完成


子类


public class FileInputStream extends InputStream{
    public FileInputStream(String name) throws FileNotFoundException
    public FileInputStream(File file) throws FileNotFoundException
}

读取示例


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
class Demo{
    public static void main(String[] args) throws IOException {
        File file = new File("demo/demo.txt");
        FileInputStream input = new FileInputStream(file);
        // 开辟缓冲区读取数据
        byte[] data = new byte[1024];
        int len = input.read(data);
        System.out.println("["  + new String(data, 0, len) + "]");
        input.close();
    }
}

75 Writer字符输出流

Writer可以直接输出字符串


public abstract class Writer 
    implements Appendable, Closeable, Flushable{
        public void write(char cbuf[]) throws IOException;
        public void write(String str) throws IOException;
    }
public class OutputStreamWriter extends Writer
public class FileWriter extends OutputStreamWriter{
    public FileWriter(String fileName, boolean append);
    public FileWriter(String fileName)
    public FileWriter(File file)
    public FileWriter(File file, boolean append)
}

代码实例


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
class Demo{
    public static void main(String[] args) throws IOException {
        File file = new File("demo/demo.txt");
        FileWriter writer = new FileWriter(file);
        writer.write("hello java");
        writer.append("你好!java!");
        writer.close();
    }
}

76 Reader字符输入流

继承关系


public abstract class Reader implements Readable, Closeable
public class InputStreamReader extends Reader
public class FileReader extends InputStreamReader{
    public FileReader(File file);
    public FileReader(String fileName);    
}

读取示例


import java.io.File;
import java.io.FileReader;
import java.io.IOException;
class Demo{
    public static void main(String[] args) throws IOException {
        File file = new File("demo/demo.txt");
        FileReader reader = new FileReader(file);
        char[] data= new char[1024];
        int len = reader.read(data);
        System.out.println(new String(data, 0, len));
        reader.close();
    }
}

字符流读取只能按照数组数据读取


77 字节流与字符流的区别

不使用close关闭

使用字节流输出 OutputStream 正常输出

使用字符流输出 Writer 无法输出,使用了缓冲区


close会强制刷新缓冲区(flush)


字节流不使用缓冲区,字符流使用缓冲区


78 转换流

字节流与字符流操作的功能转换


import java.io.*;
class Demo{
    public static void main(String[] args) throws IOException {
        File file = new File("demo/demo.txt");
        // 字节流转字符流操作
        OutputStream out = new FileOutputStream(file);
        Writer wirter = new OutputStreamWriter(out);
        wirter.write("你好");
        wirter.close();
    }
}

继承关系


OutputStream(Closeable, Flushable)
    -FileOutputStream
InputStream(Closeable)
    -FileInputStream
Writer(Appendable, Closeable, Flushable)
    -OutputStreamWriter
        -FileWriter
Reader(Readable, Closeable)
    -InputStreamReader
        -FileReader

缓存,程序中间缓冲区


字节数据:101010101…


79 综合实战:文件拷贝

实现文件拷贝操作

使用字节流


方案一:

全部读取,一次性输出

方法二:

每次读取一部分,输出一部分


import java.io.*;
class FileUtil {
    public static void copyFile(String src, String target) throws IOException {
        InputStream input = new FileInputStream(src);
        OutputStream output = new FileOutputStream(target);
        byte[] data = new byte[1024];
        int len = 0;
        while ((len = input.read(data)) != -1) {
            output.write(data, 0, len);
        }
        input.close();
        output.close();
    }
    public static void copyDir(String src, String target) throws IOException {
        File srcFile = new File(src);
        File targetFile = new File(target);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        File[] results = srcFile.listFiles();
        if (results != null) {
            for (File file : results) {
                String fileName = targetFile + File.separator + file.getName();
                if (file.isDirectory()) {
                    copyDir(file.getPath(), fileName);
                } else {
                    copyFile(file.getPath(), fileName);
                }
            }
        }
    }
}
class Demo {
    public static void main(String[] args) throws IOException {
        FileUtil.copyDir("demo", "demo2");
        System.out.println("拷贝完成");
    }
}

如果拷贝目录则使用递归拷贝

目录
打赏
0
0
0
0
58
分享
相关文章
java制作海报四:java BufferedImage 转 InputStream 上传至OSS。png 图片合成到模板(另一个图片)上时,透明部分变成了黑色
这篇文章主要介绍了如何将Java中的BufferedImage对象转换为InputStream以上传至OSS,并解决了png图片合成时透明部分变黑的问题。
210 1
揭秘Java IO流:字节流与字符流的神秘面纱!
揭秘Java IO流:字节流与字符流的神秘面纱!
70 1
Java IO流全解析:字节流和字符流的区别与联系!
Java IO流全解析:字节流和字符流的区别与联系!
174 1
15 Java IO流(File类+IO流+字节流+字符流+字节编码)
15 Java IO流(File类+IO流+字节流+字符流+字节编码)
69 3
|
8月前
|
图解java工程师学习路线
图解java工程师学习路线
290 0
一篇文章讲明白java字符流字节流
一篇文章讲明白java字符流字节流
38 0
Java IO流专家级教程:深入理解InputStream/OutputStream和Reader/Writer的内部机制
【6月更文挑战第26天】Java IO流涉及字节流(InputStream/OutputStream)和字符流(Reader/Writer),用于高效处理数据输入输出。InputStream/OutputStream处理二进制数据,常使用缓冲提升性能;Reader/Writer处理文本,关注字符编码转换。两者都有阻塞IO操作,但Java NIO支持非阻塞。示例代码展示了如何使用FileInputStream/FileOutputStream和FileReader/FileWriter读写文件。理解这些流的内部机制有助于优化代码性能。
174 0

热门文章

最新文章