当我通过一个程序来阅读文件时,我有一个疑问。我们可以使用BufferedReader
读取文件,如下所示
package com.mkyong.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
我们也可以使用BufferedInputStream
读取文件,如下所示
package com.mkyong.io;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class BufferedInputStreamExample {
public static void main(String[] args) {
File file = new File("C:\\testing.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
System.out.println(dis.readLine());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
bis.close();
dis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
所以我怀疑使用BufferedReader
和BufferedInputStream
有什么不同,而且效率更高