6. 为如下代码加上异常处理
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));//打印数组内容
6.1 改正代码,并增加如下功能。当找不到文件时,需提示用户找不到文件xxx,请重新输入文件名,然后尝试重新打开。 如果是其他异常则提示打开或读取文件失败!。
注1:里面有多个方法均可能抛出异常。
功能2:需要添加finally关闭文件。无论上面的代码是否产生异常,总要提示关闭文件ing。如果关闭文件失败,提示关闭文件失败!
6.2 结合题集6-2代码,要将什么样操作放在finally块?为什么?使用finally关闭资源需要注意一些什么?
将必须要执行的操作放在finally块,因为finally块中代码一定会执行,注意要进行try catch,因为关闭资源时可能出现异常。
6.3 使用Java7中的try-with-resources来改写上述代码实现自动关闭资源。简述这种方法有何好处?
byte[] content = null;
try(FileInputStream fis = new FileInputStream("testfis.txt"))
{
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));//打印数组内容
好处:生成代码更加简洁,try-with-resources语句在编写必须关闭资源的代码时会更容易。
7. 读取文件并组装对象
实验任务书中中的题目3:读取文件并组装对象
7.1 给出关键代码(需出现你的学号)。额外要求:捕获异常时,将错误的信息按照出错原因:行号:该行内容格式输出。
public class ReadFileUsingScanner201721123093 {
private static Scanner in;
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
int count=0;
Scanner in = new Scanner(new File("身份证号.txt"));//为myfile.txt这个File创建一个扫描器in
while(in.hasNextLine()){
String line = in.nextLine();//读出myfile.txt的下一行
count++;
Scanner lineScanner = new Scanner(line);//为每一行建立一个扫描器
lineScanner.useDelimiter(" ");//使用空格作为分隔符
try{
String a1 = lineScanner.next();//姓名
String a2 = lineScanner.next();//身份证号
String a3 = lineScanner.next();//性别
String a4 = lineScanner.next();//年龄
String a5 = lineScanner.next();//地址
while(lineScanner.hasNext()){//谨防地址只有一段
a5 += lineScanner.next();
}
System.out.println(a1+a2+a3+a4+a5);
try {
if (a1.length()==0)
throw new Exception("请填写姓名,姓名为空");
if (a2.length()==0)
throw new Exception("请填写身份证号,身份证号为空");
if (a2.length()!=18) {
throw new Exception("身份证号格式错误");
}
if (a3.length()==0)
throw new Exception("您的性别未填写");
if (!a3.equals("男") && !a3.equals("女"))
throw new Exception("性别格式错误");
if (a4.length()==0)
throw new Exception("您的年龄未填写");
if (a5.length()==0)
throw new Exception("您的地址未填写");
} catch (Exception e) {
System.out.println(e+":"+count+":"+line);
}
}catch(Exception e){
System.out.println(e+":"+count+":"+line);
}
}
}catch(FileNotFoundException e){
System.out.println(e);
}finally{
if(in!=null){
try{
in.close();
}catch(Exception e){
System.out.println(e);
}
}
}
}
}