English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Как включить текущую дату при записи исключений в файл с помощью 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() + ":\t" + 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);
      }
   }
}

Output result

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
Основной учебник
Давай посмотрим, что вам может понравиться