FileInputStream中read()方法改进
一、框架展示
框架很注重要,一定要会搭
package IO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamTest02 {
public static void main(String[] args) {
FileInputStream fis =null;
try {
fis = new FileInputStream("temp");
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
二、改进代码
1.上一篇文章中代码的问题
1.先前程序缺点:每次单独调用read方法,费时费力。
2.解决思路——一次读取多个字节——用while循环
2.用while循环实现一次读取多个
代码如下:
package IO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
//对第一个程序改进,循环方式
//解决思路——一次读取多个字节
public class FileInputStreamTest02 {
public static void main(String[] args) {
FileInputStream fis =null;
try {
fis = new FileInputStream("temp");
// 基本思路
while(true){
int readData = fis.read();
if (readData == -1){
break;
}
System.out.println(readData);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
执行结果
3.进一步的简化
package IO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamTest02 {
public static void main(String[] args) {
FileInputStream fis =null;
try {
fis = new FileInputStream("temp");
// 改造while循环
int readData = 0;
while((readData = fis.read())!= -1){
System.out.println(readData);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
总结
该代码是上一篇文章中代码的优化方案,用while循环解决了read方法的重复调用。
但read()方法是有局限的:
本文中的“temp”文件为方便演示体积很小,不容易出现问题。而在实际应用当中通常不可能只传输这么小的文件,而read()方法只能一次读取一个字节(Byte),这样内存硬盘交互太频繁,时间和资源基本都耗费在交互上了。
这个问题我们可以用数组来解决,详细方式请看下文:
https://blog.csdn.net/m0_57497737/article/details/118662359.