如何在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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP