java-异常

6. 为如下代码加上异常处理

6.1 改正代码,并增加如下功能。当找不到文件时,需提示用户找不到文件xxx,请重新输入文件名,然后尝试重新打开。 如果是其他异常则提示打开或读取文件失败!

修改代码如下:

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

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


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

  • finally语句必执行,所以finally一般用于释放资源。因为不论是否发生异常Finally块中的代码都会被执行。需要注意的是,使用Finally关闭资源时也有可能发生异常,要对其作try-catch处理。

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

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

public class Main1 {
	public static void main(String[] args) throws IOException{
		Scanner sc = new Scanner(System.in);
		byte[] content = null;
		String file = sc.next();

			try(FileInputStream f = new FileInputStream(file)){
				int bytesAvailabe = f.available();//获取该文件可用字节数
				if(bytesAvailabe > 0) {
					content = new byte[bytesAvailabe];//创建可容纳文件大小的数组
					f.read(content);//将文件内容读入数组
				}
				System.out.println(Arrays.toString(content));
			}catch(FileNotFoundException e) {
				System.out.println("找不到文件,请重新输入文件名");
				file = sc.next();
			}
			catch(IOException e) {
				System.out.println("打开或读取文件失败");
				System.exit(0);
			}
		}
	
}
  • try-with-resources简化了代码,不需要自己进行close()操作,实现了自动关闭资源的功能。

7. 读取文件并组装对象

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

代码

package test;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Main2 {
	public static void main(String[] args) throws FileNotFoundException, NoSuchElementException {
		    int n=0;
		    ArrayList<User>users=new ArrayList<User>();
		    Scanner in = new Scanner(new File("D:\\text.txt"));//为myfile.txt这个File创建一个扫描器in
	        while(in.hasNextLine()){
	        	
	            String line = in.nextLine();//读出myfile.txt的下一行
	            n++;
	            Scanner lineScanner = new Scanner(line);//为每一行建立一个扫描器
	     
	            lineScanner.useDelimiter(" ");//使用空格作为分隔符
	           
	            User user = null;
	           try {  
	        	   	String name = lineScanner.next();//姓名
	        	   	String id = lineScanner.next();//学号
					String age = lineScanner.next();//年龄
					user = new User(name,id,age,n);
					users.add(user);
	           }catch(NoSuchElementException e) {
	                System.out.println(e);
	            }
	        }
	      //  Collections.sort(users, new AgeComparator());
	        for(int i=0;i<users.size();i++)
	            System.out.println(users.get(i).toString());

	 }

}
class User{
	String name;//姓名
    String id;//身份证号
    String age;//年龄
    int n;
    public int getn() {
		return n;
	}
	public void setn(int n) {
		this.n=n;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}

    public  User(String name,String id,String age,int n) throws NoSuchElementException{
    	this.name=name;
    	this.id=id;
    	this.age=age;
    	this.n=n;
    	if(Integer.parseInt(age)<0)
    		throw new NoSuchElementException("第"+n+"行发生错误: "+"年龄小于于0,不正常" );
    }
	@Override
	public String toString() {
		return "User [name=" + name+ ", id="+id + ", age=" + age + "]";
	}
    
}


运行结果

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

  • 解:将所有出错信息存入文件中以便查找。
posted @ 2018-11-19 00:45  晴天*  阅读(119)  评论(0编辑  收藏  举报