2011年计算机等级考试二级JAVA学习(18)
1.1.3.2 调整 JavaTM I/O 性能 #
1.1.3.2.1 加速I/O的基本规则
作为这个讨论的开始,这里有几个如何加速I/O的基本规则:
#
1. 避免访问磁盘 #
2. 避免访问底层的操作系统 #
3. 避免方法调用 #
4. 避免个别的处理字节和字符 #
很明显这些规则不能在所有的问题上避免,因为如果能够的话就没有实际的I/O被执行。考虑下面的计算文件中的新行符('\n')的三部分范例。
#
方法1: read方法
第一个方法简单的使用FileInputStream的read方法: #
import java.io.*; #
public class intro1 { #
public static void main(String args[]) {
#
if (args.length != 1) {
#
System.err.println("missing filename");
#
System.exit(1); #
} #
try {
#
FileInputStream fis = new FileInputStream(args[0]); #
int cnt = 0;
int b; #
while ((b = fis.read()) != -1) {
if (b == '\n') #
cnt++;
#
} #
fis.close(); #
System.out.println(cnt); #
} catch (IOException e) {
#
System.err.println(e); #
} #
} #
}然而这个方法触发了大量的底层运行时系统调用--FileInputStream.read--返回文件的下一个字节的本机方法。
#