如何使用 Java 向现有文件添加/附加内容?

java 8object oriented programmingprogramming更新于 2025/11/20 6:36:17

在大多数情况下,如果您尝试使用 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 {
      //检索日志文件
      Path logFile = Paths.get("ExceptionLog.txt");
      //准备要记录的数据
      byte bytes[] = ("\r
"+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

相关文章