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

Java에서 데이터를 파일에 추가하는 방법

대부분의 경우, java.io 패키지의 클래스를 사용하여 파일에 내용을 쓰려고 시도하면 파일이 덮어쓰여집니다. 즉, 파일에 존재하는 데이터를 지우고 새 데이터를 추가합니다.

예를 들어, 예외를 파일에 기록하는 경우(레코드어 프레임워크를 사용하지 않는 경우) 파일의 다음 줄에 데이터(메시지)를 추가해야 합니다.

java.nio 패키지의 Files 클래스를 사용하여 이 작업을 수행할 수 있습니다. 이 클래스는write()를 받아들이는

  • Path 클래스의 객체는 파일을 나타냅니다.

  • 데이터를 파일에 저장하는 바이트 배열

  • OpenOption(인터페이스) 타입의 변수를 값을 전달하여 StandardOpenOption 열거형의 요소 중 하나에 사용할 수 있습니다. 이 열거형 요소는10개의 옵션, 즉 APPEND, CREATE, CREATE_NEW, DELETE_ON_CLOSE, DSYNC, READ, SPARSE, SYNC, TRUNCATE_EXISTING, WRITE가 있습니다.

파일 경로, 추가할 데이터를 포함한 바이트 배열 및 옵션 StandardOpenOption.APPEND를 전달하여 이 메서드를 호출할 수 있습니다.

예제

다음 Java 프로그램은 배열을 저장하는5개의 정수 값을 사용자가 배열에서 두 개의 요소(인덱스)를 선택하여 그들 사이에서 나누기를 수행하도록 합니다. 이 코드를 try 블록에 포함하여 ArithmeticException, InputMismatchException, ArrayIndexOutOfBoundsException의 세 가지 catch 블록을 포함합니다. 각각의 호출에서 이를writeToFile()}메서드를 사용합니다.

이 메서드는 예외 객체를 받아들여 Files 클래스의write()이 메서드는 파일에 추가합니다.

public class LoggingToFile {
   private static void writeToFile(Exception e) throws IOException {
      //로그 파일을 검색합니다
      Path logFile = Paths.get("ExceptionLog.txt");
      //기록할 준비된 데이터
      byte bytes[] = ("\r\n"+LocalDateTime.now()+: "+e.toString()).getBytes();
      //이 예외를 파일에 추가합니다
      Files.write(logFile, bytes, StandardOpenOption.APPEND);
      System.out.println("예외가 파일에 기록되었습니다.");
   }
   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)
      try {
         int a = sc.nextInt();
         int b = sc.nextInt();
         int result = (arr[a])/(arr[b]);
         System.out.println("결과: "+arr[a]+"/"+arr[b]+: "+result);
      }
         System.out.println("경고: 선택한 위치가 배열에 없습니다.");
         writeLogToFile(ex);
      }catch(ArithmeticException ex) {
         System.out.println("Warning: You cannot divide an number with 0");
         writeLogToFile(ex);
      }catch(InputMismatchException ex) {
         System.out.println("Warning: You have entered invalid input");
         writeLogToFile(ex);
      }
   }
}

output1

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)
2
4
Warning: You cannot divide an number with 0
Exception logged to your file

output2

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)
5
12
Warning: You have chosen a position which is not in the array
Exception logged to your file

output3

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)
hello
Warning: You have entered invalid input
Exception logged to your file

ExceptionLog.txt

2019-07-19T17:57:09.735: java.lang.ArithmeticException: / by zero
2019-07-19T17:57:39.025: java.lang.ArrayIndexOutOfBoundsException: 12
2019-07-19T18:00:23.374: java.util.InputMismatchException