InputStream 基类,抽象类
FileInputStream 读取文件的字节流
BufferedInputStream 缓冲输入字符流
package file; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; public class test {
public static void main(String[] args) throws IOException {
// readTest1();
// readTest2();
// readTest3();
readTest4(); //效率最高
} //方式4:使用缓冲数据配合循环读取
public static void readTest4() throws IOException {
long startTime = System.currentTimeMillis();
File file = new File("F:\\a.txt");
FileInputStream fileInputStream = new FileInputStream(file);
//建立缓冲字节数组,读取文件的数据。
byte[] buf = new byte[1024];
int content = 0;
while((content = fileInputStream.read(buf) ) != -1){
System.out.println("内容是:"+ content);
}
fileInputStream.close();
long endTime = System.currentTimeMillis();
System.out.println("读取时间是:"+ (endTime-startTime));
} //方式3、使用 缓冲数据 读取 无法读取完整一个文件的数据:
public static void readTest3() throws IOException {
File file = new File("F:\\a.txt");
FileInputStream fileInputStream = new FileInputStream(file);
//建立缓冲字节数组,读取文件的数据。
byte[] buf = new byte[1024];
int length = fileInputStream.read(buf); //数据已经存储到了字节数组中了,read返回值是本次读取了几个字节数据到字节数组中
System.out.println("length:" + length);
//使用字节数组构建字符串
String content = new String(buf,0,length); //读取长度个,一定要加length,因为不加length,会覆盖,比如,aaaabbb,读取之后会变成aaaabbba。
System.out.println("内容是:"+content);
fileInputStream.close();
} //方式2、使用循环读取文件的数据
public static void readTest2() throws IOException {
File file = new File("F:\\a.txt");
FileInputStream fileInputStream = new FileInputStream(file);
//读取文件的数据
int content = 0;
while((content = fileInputStream.read())!=-1) {
System.out.print((char)content);
}
fileInputStream.close();
} //方式1、
public static void readTest1() throws IOException {
//1.找到目标文件
File file = new File("F:\\a.txt");
//建立数据的输入通道
FileInputStream fileInputStream = new FileInputStream(file);
//读取文件中的数据
int content = fileInputStream.read(); //每次读取一个字节
System.out.println("读取的内容.."+ content);
//关闭资源
fileInputStream.close();
}
}