package Inputstream;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.testng.annotations.Test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStream_ {
public static void main(String[] args) {
}
@Test
//这个方法是使用最低效率(一个字节一个字节读入)的方法
public void m1() throws IOException {
int b = 0;
FileInputStream fileInputStream = new FileInputStream("D:\\学习\\Java学习\\IO\\new2.txt");
try {
while ((b=fileInputStream.read())!=-1){
System.out.print((char)b);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
fileInputStream.close();
}
}
@Test
//这个方法是最常用的高效率(一次读入自定义大小的byte数组个字节)的方法
public void m2() throws IOException {
int b =0;
//自定义一个大小为1024字节的数组
byte[] but = new byte[1024];
FileInputStream fileInputStream = new FileInputStream("D:\\学习\\Java学习\\IO\\new2.txt");
try {
//fileInputStream.read(but)的返回值是读取到的数据的字节数
while((b = fileInputStream.read(but))!=-1){
//将but字节数组中的数据转换成一个字符串输出
System.out.println(new String(but,0,b));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
fileInputStream.close();
}
}
}
FileInputStream的两种读入方式
于 2022-04-17 22:19:59 首次发布