java io流 运行错误时,保存异常到文件里面

java io流

运行错误时,保存异常到文件里面

下面这个实例,运行后,输入数字,为正确,如果输入字符串,则报错,保存错误信息

//运行错误时,保存异常到文件里面

//下面这个实例,运行后,输入数字,为正确,如果输入字符串,则报错,保存错误信息

import java.io.*;
import java.util.*;

public class Index{
    public static void main(String[] args) throws Exception{
        

        try{
            //创建文件
            PrintStream zhengque = new PrintStream("D:/zhegnque.txt");
            PrintStream cuowu = new PrintStream("D:/cuowu.txt");
            
            //使用扫描仪
            Scanner input = new Scanner(System.in);
            int shuzi;
            
            System.setOut(zhengque);    //如果没有报错,存储到这个文件
            System.setErr(cuowu);        //如果有报错,存储到这个文件,此函数跟下面catch里面的内容关联
            
            while(true){
                shuzi = input.nextInt();
                System.out.println("输入的数字为:"+shuzi);
            }
        }
        catch(Exception e){
            System.err.println("执行错误");
        }
        
        
        
    }
}
原文地址:https://www.cnblogs.com/phpyangbo/p/5965752.html