news.txt = hello everyone
news01.txt = everyonebuddy,hellohi
package file.InputStream_;
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStream_ {
public static void main(String[] args) {
}
/*
*这样单字符读取太慢,利用数组会比较快
*/
@Test
public void readFile01() throws IOException {
String filepath = "d:\\news.txt";
int readData = 0;
FileInputStream fileInputStream = null;
try {//创建FileInputStream,用于读取d:\news.txt文件
fileInputStream = new FileInputStream(filepath);
//从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
//如果返回-1,表示读取完毕
while((readData = fileInputStream.read()) != -1){
System.out.print((char)readData);//转成字符显示
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {//关闭文件流,释放资源
fileInputStream.close();
}
}
@Test
public void readFile02() throws IOException {
String filepath = "d:\\news01.txt";
byte[] buff = new byte[8];//一次取8个字节
int readlen = 0;
FileInputStream fileInputStream = null;
try {//创建FileInputStream,用于读取d:\news.txt文件
fileInputStream = new FileInputStream(filepath);
//从该输入流读取最多b.length字节的数据到字节数组,此方法将阻塞,
//如果返回-1,表示读取完毕
while((readlen = fileInputStream.read(buff)) != -1){
System.out.print(new String(buff,0,readlen));//打印buff数组,索引从0开始打印,每次最多打印8个字符
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {//关闭文件流,释放资源
fileInputStream.close();
}
}
}
输出1:
输出2: