如何使用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塊中,該塊包含三個catch塊,分別捕獲ArithmeticException、InputMismatchException和ArrayIndexOutOfBoundsException異常。在每個catch塊中,我們都呼叫writeToFile()方法。

此方法接受一個異常物件,並使用Files類的write()方法將其追加到檔案。

public class LoggingToFile {
   private static void writeToFile(Exception e) throws IOException {
      //Retrieving the log file
      Path logFile = Paths.get("ExceptionLog.txt");
      //Preparing the data to be logged
      byte bytes[] = ("\r
"+LocalDateTime.now()+": "+e.toString()).getBytes();       //Appending the exception to your file       Files.write(logFile, bytes, StandardOpenOption.APPEND);       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)");       try {          int a = sc.nextInt();          int b = sc.nextInt();          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 an number with 0");          writeLogToFile(ex);       }       catch(InputMismatchException ex) {          System.out.println("Warning: You have entered invalid input");          writeLogToFile(ex);       }    } }

輸出1

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

輸出2

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

輸出3

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

更新於:2019年9月12日

406 次檢視

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.