如何在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年8月6日

656 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.