當使用 FileOutputStream 在 java 中將異常記錄到檔案中時,如何包括當前日期?
有一些可用的日誌框架可以將您的資料記錄到檔案中。您還可以定義自己的方法。在任一情況下,要將當前時間新增到已記錄的異常中,可以使用 LocalDateTime 類。
它是一個不可變類,代表日期時間,它將日期時間儲存為 年-月-日-時-分-秒。此類的 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP