如何使用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()方法。

此方法接受异常对象,并使用write()Files类的方法将其附加到文件中。

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("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