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

Java에서 FileOutputStream를 사용하여 파일에 예외를 기록할 때 현재 날짜를 어떻게 포함하나요?

데이터를 파일에 기록하는 로그 기록 프레임워크가 여러 가지 사용할 수 있습니다. 또한 자신의 메서드를 정의할 수도 있습니다. 어떤 경우이든 기록된 예외에 현재 시간을 추가하려면LocalDateTime클래스

데이터를 기록하는 파일에 현재 시간을 추가할 수 있는 로그 기록 프레임워크가 여러 가지 있습니다. 또한 자신의 메서드를 정의할 수도 있습니다. 어떤 경우이든 현재 시간을 기록된 예외에 추가하려면year-month-day-hour-minute-secondnow()이 클래스의 메서드는 현재 날짜와 시간을 반환합니다.

현재 날짜와 시간을 예외 메시지에 연결하여 필요한 파일에 기록하는 이 메서드를 사용하세요.

예제

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("배열: " + "+Arrays.toString(arr));
      System.out.println("이 배열에서 분자와 분모(0이 아닌)를 선택하세요 (위치 0에서 입력하세요 5})");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a]);/(arr[b]);
         System.out.println("" + "Result of " + (arr[b]));+arr[a]+"/"+arr[b]+: "+result);
      }catch(ArrayIndexOutOfBoundsException ex) {
         System.out.println("경고: 배열에 없는 위치를 선택했습니다");
         writeLogToFile(ex);
      }catch(ArithmeticException ex) {
         System.out.println("경고: 0으로 숫자를 나눌 수 없습니다");
         writeLogToFile(ex);
      }
   }
}

출력 결과

입력 3 각각의 정수 값을 하나씩 입력하세요:
배열: [10, 20, 30, 2, 0, 8]
이 배열에서 분수의 분자와 분모(0이 아닌)를 선택하세요 (위치 0에서 입력하세요 5)
1
4
경고: 0으로 숫자를 나눌 수 없습니다
예외가 파일에 기록되었습니다