解析IO操作InputStream、OutputStream、InputStreamReader OutputStreamWriter、BufferedReader BufferedWriter

1、InputStream、OutputStream
处理字节流的抽象类
InputStream 是字节输入流的所有类的超类,一般我们使用它的子类,如FileInputStream等.
OutputStream是字节输出流的所有类的超类,一般我们使用它的子类,如FileOutputStream等.

//以下是FileInputStream读取文件输出打印为例
String path = "D:/789.txt";
File file = new File(path);

StringBuffer stringBuffer1 = new StringBuffer();

FileInputStream fileInputStream = new FileInputStream(file);
int index;
while((index = fileInputStream.read()) != -1){
    char strChar = (char)index;
    stringBuffer1.append(strChar);
}
System.out.println(stringBuffer1.toString());
fileInputStream.close();

2.InputStreamReader OutputStreamWriter
处理字符流的抽象类
InputStreamReader 是字节流通向字符流的桥梁,它将字节流转换为字符流.
OutputStreamWriter是字符流通向字节流的桥梁,它将字符流转换为字节流.

//以下是InputStreamReader读取文件输出打印为例
String path = "D:/789.txt"; 
File file = new File(path);
StringBuffer stringBuffer2 = new StringBuffer();

FileInputStream fileInputStream = new FileInputStream(file);
//处理中文乱码 设置utf-8
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
int index;
while((index = inputStreamReader.read()) != -1){
    char strChar = (char)index;
    stringBuffer2.append(strChar);
}
System.out.println(stringBuffer2.toString());
inputStreamReader.close();
fileInputStream.close();

3.BufferedReader BufferedWriter
BufferedReader 由Reader类扩展而来,提供通用的缓冲方式文本读取,readLine读取一个文本行,
从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取。
BufferedWriter 由Writer 类扩展而来,提供通用的缓冲方式文本写入, newLine使用平台自己的行分隔符,
将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。

String path = "D:/789.txt";
File file = new File(path);
//以下是BufferedReader读取文件输出打印为例 
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

StringBuffer stringBuffer3 = new StringBuffer();
String str;
while((str = bufferedReader.readLine()) != null){
    stringBuffer3.append(str);
}
System.out.println(stringBuffer3.toString());
bufferedReader.close();
inputStreamReader.close();
fileInputStream.close();

你可能感兴趣的:(java)