byte[] content = null;
FileInputStream fis = new FileInputStream("testfis.txt");
int bytesAvailabe = fis.available();//获得该文件可用的字节数
if(bytesAvailabe>0){
content = new byte[bytesAvailabe];//创建可容纳文件大小的数组
fis.read(content);//将文件内容读入数组
}
System.out.println(Arrays.toString(content));//打印数组内容
package twentyth;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Six {
/*public static void main(String[] args) {
byte[] content = null;
Scanner sc=new Scanner(System.in);
FileInputStream fis=null;
while(sc.hasNext()) {
String str=sc.next();
try {
fis = new FileInputStream(str);
int bytesAvailabe = fis.available();//获得该文件可用的字节数
if(bytesAvailabe>0){
content = new byte[bytesAvailabe];//创建可容纳文件大小的数组
fis.read(content);//将文件内容读入数组
}
System.out.println(Arrays.toString(content));//打印数组内容
} catch (Exception e) {
if(e instanceof FileNotFoundException) {
System.out.println("找不到文件"+str+",请重新输入文件名");
}
else {
System.out.println("打开或读取文件失败!");
break;
}
}finally {
if(fis!=null){
try{
fis.close();
System.out.println("关闭文件ing");
}catch(NullPointerException e){//判断是否是空指针异常
System.out.println(e);
}
}
}
} */
public static void main(String[] args) throws IOException{
byte[] content = null;
try(FileInputStream fis = new FileInputStream("testfis.txt")){//在try的圆括号中写入将要关闭资源的对象
int bytesAvailabe = fis.available();//获得该文件可用的字节数
if(bytesAvailabe>0){
content = new byte[bytesAvailabe];//创建可容纳文件大小的数组
fis.read(content);//将文件内容读入数组
}
}catch(Exception e){
System.out.println(e);
}
System.out.println(Arrays.toString(content));//打印数组内容
}
}
6.1 改正代码,并增加如下功能。当找不到文件时,需提示用户找不到文件xxx,请重新输入文件名
,然后尝试重新打开。 如果是其他异常则提示打开或读取文件失败!
。
注1:里面有多个方法均可能抛出异常。
功能2:需要添加finally
关闭文件。无论上面的代码是否产生异常,总要提示关闭文件ing
。如果关闭文件失败,提示关闭文件失败!
6.2 结合题集6-2
代码,要将什么样操作放在finally块?为什么?使用finally关闭资源需要注意一些什么?
try{}catch{}放入finally中,因为关闭文件可能存在异常。
6.3 使用Java7中的try-with-resources
来改写上述代码实现自动关闭资源。简述这种方法有何好处?
尝试自动关闭资源的对象生成写在try之后的圆括号中,无需判断是否为null,也避免了在关闭时产生的其它异常,使整个代码更简洁。
原文:https://www.cnblogs.com/huyaoco/p/9980769.html