字节流与字符流的区别

image

字节流例子:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class OutputStreamDemo05 {
    public static void main(String[] args) throws IOException {
        File f = new File("f:" + File.separator + "my honey.txt");
        OutputStream out = new FileOutputStream(f);
        String str = "Miss you so much,joss lea.";
        byte[] b = str.getBytes();
        out.write(b);
        // out.close();//不关闭也会保存到硬盘
    }
}

字符流例子:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class OutputStreamDemo06 {
    public static void main(String[] args) throws IOException {
        File f = new File("f:" + File.separator + "first love.txt");
       Writer writer = new FileWriter(f);
        String str = "belive the future.";
        writer.write(str);
        writer.flush();// 强制刷新缓存区至硬盘
        // writer.close();//字符流操作使用了缓存区,不关闭不刷新
    }
}

所有的文件在硬盘或在传输时都是以字节的方式进行的,包括图片等都是按自己的方式存储的,而字符是只有在内存中才会形成,所以在开发中,字节流使用较为广泛。

原文地址:https://www.cnblogs.com/vonk/p/3921276.html