1、字符流:Reader和Writer
>字符流是以"char"为单位读写数据的,因此字符流【仅适合读写文本数据】
2、转化流:InputStreamReader和OutputStreamWriter
>它们是常见的字符流的实现类,实际开发中我们不会直接操作这对流,但是在流的连接 中它是重要的一环。
>由于其他的高级字符流都只能连接在其他字符流上,是不能直接连接在字节流上使用的 ;因此转换流是唯一一个可以连接在字节流上的字符流,而其他的字符流可以连接在它上 因此转换流起到了"转换器"的作用,在流连接中就可以完成字符与字节流的串联工作了。
/**
* 使用转换输入流测试读取文本数据
*/
public class ISRDemo {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("./src/main/java/io/ISRDemo.java");
InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
/*
字符流也有:int read()
该方法不是读取1个字节,而是读取一个字符(一个char)。
一个char占2个字节(16位2进制),返回的int值低16位有数据。如果返回值为
-1则表达流读取到了末尾
*/
int d;
while((d = isr.read())!=-1) {
System.out.print((char) d);
}
isr.close();
}
}
3、缓冲字符流:BufferedReader和BufferedWriter
>缓冲字符流内部维护一个默认8192长度的char数组,块读文本数据。 特点:可以按行读取字符串
public class BRDemo {
public static void main(String[] args) throws IOException {
//将当前源代码按行读取并输出到控制台上
FileInputStream fis = new FileInputStream("./src/main/java/io/BRDemo.java");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String line;
/*
BufferedReader提供了读取一行字符串的方法:
String readLine()
返回一行字符串,返回的字符串中不含有本行末尾的换行符。
如果本行为空行(只有换行符)那么返回值为空字符串。
如果流读取到了末尾,则返回值为null。
*/
while((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
4、自动行刷输出流:PrintWrite
>PrintWriter是具有自动行刷新功能的缓冲字符输出流,其内部总是连接BufferedWriter。
>可以按行写出字符串 ,可以自动行刷新
public class Test3 {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
FileOutputStream fos = new FileOutputStream("pw2.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(bw,true);
while (true) {
System.out.println("请输入内容:");
String line = scan.nextLine();
if ("exit".equals(line)) {
break;
}
pw.println(line);
}
System.out.println("输出完毕");
pw.close();
}
}