在程序运行过程中,可能会发生你意想不到的事情,比如说异常,我们把这些异常信息如果保存到文件中去,我们就可以很方便的查看到哪里出现了问题,以便去定位解决这样的问题。所保存的文件我们通常称之为日志文件。那咋把异常信息干到文件中去呢。

通常异常对象调用自己的printStackTrace()方法是将信息直接打印在控制台上的。如果将目的地控制台修改成本地的Log文件不就OK了吗,谁来干这个事情呢,System.setOut(out)可以将目的地进行修改。这里的out可以使用PrintStream对象。

各种倒腾打印异常信息至本地文件不再是梦。示例代码如下:

public static void main(String[] args) throws IOException {
	
		int[] arr = new int[2];
		try {
			arr[2]=3;
		} catch (Exception e) {
			Date d = new Date();
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-HH-mm");
			String s =sd.format(d);
			
			PrintStream out = new PrintStream("c:\\exception.log");
			out.print(s+":");
			System.setOut(out);
			e.printStackTrace(System.out);
		}
	}