字节流和子符流的读写及区别

package readre;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class readwriter {

/**
* @param args
*/
public static void main(String[] args) {
//创建文件夹
File path = new File("d:\test\");
if(!path.exists()){
path.mkdir();
}
//字节流写
File file = new File(path+"\"+"test.txt");
try {
FileOutputStream out = new FileOutputStream(file);
String s = "Hello World1";
byte[] b = s.getBytes();
try {
out.write(b);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//字节流读
try {
FileInputStream in = new FileInputStream(file);
try {
byte[] b = new byte[1024];
int len = in.read(b);
in.close();
System.out.println(new String(b,0,len));
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//子符流写
try {
FileWriter writer = new FileWriter(file);
String str ="Hello World2";
writer.write(str);
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}

//子符流读
try {
FileReader reader = new FileReader(file);
try {
char[] c = new char[1024];
int len2 = reader.read(c);
System.out.println(new String(c,0,len2));
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}





















}

}

2. 字节流与字符流的区别
    2.1 要把一片二进制数据数据逐一输出到某个设备中,或者从某个设备中逐一读取一片二进制数据,不管输入输出设备是什么,我们要用统一的方式来完成这些操作,用一种抽象的方式进行描述,这个抽象描述方式起名为IO流,对应的抽象类为OutputStream和InputStream,不同的实现类就代表不同的输入和输出设备,它们都是针对字节进行操作的。
    
    2.2 在应用中,经常要完全是字符的一段文本输出去或读进来,用字节流可以吗?计算机中的一切最终都是二进制的字节形式存在。对于“中国”这些字符,首先要得到其对应的字节,然后将字节写入到输出流。读取时,首先读到的是字节,可是我们要把它显示为字符,我们需要将字节转换成字符。由于这样的需求很广泛,人家专门提供了字符流的包装类。

    2.3 底层设备永远只接受字节数据,有时候要写字符串到底层设备,需要将字符串转成字节再进行写入。字符流是字节流的包装,字符流则是直接接受字符串,它内部将串转成字节,再写入底层设备,这为我们向IO设别写入或读取字符串提供了一点点方便。

    字符向字节转换时,要注意编码的问题,因为字符串转成字节数组,
    其实是转成该字符的某种编码的字节形式,读取也是反之的道理。

原文地址:https://www.cnblogs.com/zszitman/p/5806046.html