本帖最后由 RedProtector 于 2015-8-17 10:12 编辑
如下代码:import java.io.*;
public class FileReaderTest {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("IO流.txt");
//第一次读取
long time = System.currentTimeMillis();
readChar(fr);
long timereadChar = System.currentTimeMillis();
System.out.println("time Read char is = " + (timereadChar-time));
//第二次读取
long time2 = System.currentTimeMillis();
readToBuf(fr);
long timeReadBuf = System.currentTimeMillis();
System.out.println("time Read to Buf is = " + (timeReadBuf-time2));
}
private static void readChar(FileReader fr) throws IOException {
//设每个读取到的字符整数值为ch.
int ch = 0;
//循环读取字符,直到流的末尾
while((ch = fr.read()) != -1){
//将读取到的字符,强制转换为 char
System.out.print((char) ch);
}
System.out.print("\n");
}
private static void readToBuf(FileReader fr) throws IOException {
//定义一个字符缓冲区,用于存放读到的字符。
char[] buf = new char[50];
//设刚开始读到的字符为0
int len = 0 ;
//一直循环读取字符到缓冲区中,直到读到流的末尾。
while((len = fr.read(buf)) != -1){
//将每次读满的缓冲区中的字符,变成字符串打印出来。
System.out.println(new String(buf , 0 , len));
}
}
}
假设IO流.txt文件里的字符为"abcdefg"
问题:
为何运行结果为:
abcdefg
time Read char is = *
time Read to Buf is= *
而不是:
abcdefg
time Read char is = *
abcdefg
time Read to Buf is= *
|
|