zoukankan      html  css  js  c++  java
  • Java作业09-异常

    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。如果关闭文件失败,提示关闭文件失败!

    代码改造:

    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Main {
    	public static void main(String[] args) {
    		@SuppressWarnings("resource")
    		Scanner sc = new Scanner(System.in);
    		byte[] content = null;
    		FileInputStream fis = null;
    		while (true) {
    			String file = sc.next();
    			try {
    				fis = new FileInputStream(file);
    				int bytesAvailabe = fis.available();// 获得该文件可用的字节数
    				if (bytesAvailabe > 0) {
    					content = new byte[bytesAvailabe];// 创建可容纳文件大小的数组
    					fis.read(content);// 将文件内容读入数组
    				}
    				System.out.println(Arrays.toString(content));// 打印数组内容
    			} catch (FileNotFoundException e) {
    				System.out.println("找不到文件  " + file + ",请重新输入文件名");
    			} catch (Exception e) {
    				System.out.println("打开或读取文件失败!");
    			} finally {
    				try {
    					System.out.println("关闭文件ing");
    					fis.close();
    				} catch (Exception e) {
    					System.out.println("关闭文件失败!");
    				}
    			}
    		}
    	}
    }
    

    6.2 结合题集6-2代码,要将什么样操作放在finally块?为什么?使用finally关闭资源需要注意一些什么?

    将始终需要执行的代码放在finally块中。因为不论是否发生异常,finally块中的代码都会被执行。使用finally块关闭资源时也有可能发生异常,要对其作try-catch捕获处理。

    6.3 使用Java7中的try-with-resources来改写上述代码实现自动关闭资源。简述这种方法有何好处?

    使用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){
        e.printStackTrace();
    }
    
    System.out.println(Arrays.toString(content));
    

    好处:简化代码,在try语句块执行结束后,自动调用close()函数,自动关闭资源。

    7. 读取文件并组装对象(文件ReadFileUsingScanner.java)

    7.1 给出关键代码(需出现你的学号)。额外要求:捕获异常时,将错误的信息按照出错原因:行号:该行内容格式输出。

    关键代码

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.NoSuchElementException;
    import java.util.Scanner;
    
    public class ReadFileUsingScanner {
    	public static <User> void main(String[] args) throws FileNotFoundException {
    		Scanner in = new Scanner(new File("身份证号.txt"));//为myfile.txt这个File创建一个扫描器in
    		int n = in.nextInt();
    		while (in.hasNextLine()) {
    			String line = in.nextLine();// 读出myfile.txt的下一行
    			n++;
    			@SuppressWarnings("resource")
    			Scanner lineScanner = new Scanner(line);// 为每一行建立一个扫描器		
    			lineScanner.useDelimiter(" ");// 使用空格作为分隔符	
    			try {
    				String name = lineScanner.next();// 姓名
    				String id = lineScanner.next();// 身份证号
    				String gender = lineScanner.next();// 性别
    				String age = lineScanner.next();// 年龄
    				String address = lineScanner.next();// 地址
    				while (lineScanner.hasNext()) {// 谨防地址只有一段
    					address += lineScanner.next();
    				}
    				System.out.println(name+id+gender+age+address);
    			} catch (NoSuchElementException e) {
    				System.out.println("错误原因:"+ e + "行号:"+n+"该行内容为:" + line);
    			}
    		}
    	   in.close();
    	}
    }
    
    

    7.2 如果文件有上万行文本,出错的信息可能有很多行,如果将出错信息直接输出到控制台容易被忽略,请问如何解决?

    方法:将所有出错信息存入文本文件后输出。

  • 相关阅读:
    cf 559a **
    poj 2599 单调栈 ***
    Unicode(UTF-8, UTF-16)令人混淆的概念
    Uber Go 语言编程规范
    深入理解 Go Channel
    如何使用 GZIP 来优化网站
    跨域资源共享 CORS 详解 [转载]
    使用dig查询DNS解析过程
    golang 实现简单DNS服务器
    一文看懂JS的异步
  • 原文地址:https://www.cnblogs.com/78tian/p/9981154.html
Copyright © 2011-2022 走看看