字节流:
字节流是处理的基本单位是单个的字节,在java中有两个最基本的抽象字节流类。
InputStream 和 OutputStream 均为抽象类
在InputStream中有一个最基本的方法,从字节流中读取一个字节,若到了流的末尾则返回-1,用这个方法每读一个字符就会进行一次系统读取请求,效率较低。另一个重载的方法可以读取多个字节,但在底层仍然是调用的read()
方法
public abstract int read() throws IOException
public abstract int read(byte[]) throws IOException
使用方法
在Java中有些Stream能从文件或者其他地方获取字节,另一些Stream虽然不具备这一功能,但是却能把字节变为更有用的格式,例如:
FileInputStream fin = new FileInputStream("employee.dat");
DataInputStream din = new DataInputStream(fin);
double s = din.readDouble();
字符流:
在Java中字符流的基本单位是Unicode码元(2字节)。
输出字符流OutputStreamWriter:把要写入文件的字符序列(Unicode)转换为指定编码方式下的字节序列,然后写入文件中,其中指定编码为本地系统的编码。
出入字符流InputStreamReader:把要读取的字节序列按指定方式解码为Unicode存入内存中。
例如:
InputStreamReader in = new InputStreamReader(System.in);
InputStreamReader in = new InputStreamReader(new FileInputStream("kremlin.dat", "ISO8859_5"));
使用方法:
写字符
PrintWriter out = new PrintWriter(new FileWriter("employee.txt"));
String name = "China!";
out.println(name);
根据运行系统的不同,println
会添加不同的end-of-line(Windows:”\r\n”,UNIX:”\n”),可以通过System.getProperty("line.separator")
得到。
读字符
在Java1.5之前,唯一的方法就是使用BufferedReader,在新的版本中可以使用功能强大的Scanner
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("employee.txt"), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
do something
}