如何使用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