Java控制台I/O、带缓冲的字符流I/O的示例(并与字节流I/O比较)
package Exp7;
import java.io.*;
public class Example7_5_3 {
public static void main(String[] args) {
File file;
System.out.print("请输入一串字符:");
try {
byte[]b = new byte[128]; //定义字节数组 //int []a=new int[20]; //基类型
//以回车作为结束符(占2个字节)
int count=System.in.read(b); //接收键盘(输入流对象)输入,返回数组长度(包含了回车符占用的2个字节)
//InputStream is = System.in; //字节输入流
//一个国际(中文)字符在内存里占用的字节与使用编码有关,如gbk占用2字节,utf-8占用3字节,utf-16占用4字节
file = new File("d:" + File.separator + "Code" + File.separator + "tmp123.txt");//新建文件
FileOutputStream fos = new FileOutputStream(file); //创建文件输出流(字节流)对象
fos.write(b,0,count); //写入
fos.flush();
fos.close();
System.out.println("文件tmp123.txt写入结束");
System.out.print("请再次输入:");
InputStreamReader isr = new InputStreamReader(System.in); //将字节流(System.in)转换为字符流
BufferedReader br = new BufferedReader(isr); //带缓冲的字符输入流
String str = br.readLine(); //遇到回车换行符时结束
System.out.println("你输入了: " +str);
file=new File("d:\\Code\\tmp456.txt");
FileWriter fw=new FileWriter(file); //创建文件输入出流(字符流)对象
fw.write(str);
fw.flush(); //
fw.close(); //关闭输入流
System.out.println("文件tmp456.txt写入结束");
System.out.println("请分别查验文件tmp123.txt和tmp456.txt的长度。");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
tmp123.txt
大小是5字节。tmp456.txt
大小是4字节。
因为字节流会读取换行等符号,而字符流不会。