在Java中使用FileOutputStream将异常记录到文件中时,如何包括当前日期?
有几种日志记录框架可用于将数据记录到文件中。您也可以定义自己的方法。无论哪种情况,要将当前时间添加到记录的异常中,都可以使用LocalDateTime类。
它是表示日期时间的不可变类,将日期时间存储为year-month-day-hour-minute-second。now()此类的方法返回当前日期时间。
使用此方法将当前日期和时间连接到您的异常消息中,并写入所需的文件。
示例
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Scanner;
public class LoggingToFile {
private static void writeLogToFile(Exception e) throws IOException {
FileOutputStream writer = new FileOutputStream("ExceptionLog.txt");
byte bytes[] = (LocalDateTime.now()+": "+e.toString()).getBytes();
writer.write(bytes);
System.out.println("Exception logged to your file");
}
public static void main(String [] args) throws IOException {
Scanner sc = new Scanner(System.in);
int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator (not 0) from this array (enter positions 0 to 5)");
int a = sc.nextInt();
int b = sc.nextInt();
try {
int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Warning: You have chosen a position which is not in the array");
writeLogToFile(ex);
}catch(ArithmeticException ex) {
System.out.println("Warning: You cannot divide a number with 0");
writeLogToFile(ex);
}
}
}输出结果
Enter 3 integer values one by one: Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator (not 0) from this array (enter positions 0 to 5) 1 4 Warning: You cannot divide a number with 0 Exception logged to your file
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短