gxwxwtx 2010-03-19 12:12
浏览 210
已采纳

以下哪种文件读取方法效率最高?如何通过代码测试其效率?

在同样的情况下(注:文件小于2M)分别运行以下代码,哪一个性能最高,速度最好?( )
A、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);
}
}
}
B、import java.io.*;
public class intro2 {
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]);
BufferedInputStream bis =
new BufferedInputStream(fis);
int cnt = 0;
int b;
while ((b = bis.read()) != -1) {
if (b == '\n')
cnt++;
}
bis.close();
System.out.println(cnt);
}
catch (IOException e) {
System.err.println(e);
}
}
}
C、import java.io.*;
public class intro3 {
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]);
byte buf[] = new byte[2048];
int cnt = 0;
int n;
while ((n = fis.read(buf)) != -1) {
for (int i = 0; i < n; i++) {
if (buf[i] == '\n')
cnt++;
}
}
fis.close();
System.out.println(cnt);
}
catch (IOException e) {
System.err.println(e);
}
}
}
A.A最快 B.B最快 C.C最快 D.都一样

  • 写回答

7条回答 默认 最新

  • wanghaolovezlq 2010-03-19 12:32
    关注

    参考下实现

    [code="java"]
    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 {
    long begin = System.nanoTime();
    FileInputStream fis = new FileInputStream(args[0]);
    int cnt = 0;
    int b;
    while ((b = fis.read()) != -1) {
    if (b == '\n')
    cnt++;
    }
    fis.close();
    long end = System.nanoTime();
    System.out.println("本次读取文件耗时为:" + (end-begin) + "毫微秒(1/1000000秒)");
    System.out.println(cnt);
    } catch (IOException e) {
    System.err.println(e);
    }
    }
    }

    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大