How to add/append content to an existing file using Java?


In most scenarios, if you try to write content to a file, using the classes of the java.io package, the file will be overwritten i.e. data existing in the file is erased and the new data is added to it.

But, in certain scenarios like logging exceptions into a file (without using logger frameworks) you need to append data (message) in the next line of the file.

You can do this using the Files class of the java.nio package. This class provides a method named write() which accepts

  • An object of the class Path, representing a file.

  • A byte array holding the data to the file.

  • A variable argument of the type OpenOption (interface) as a value to it you can pass one of the elements of StandardOpenOption enumeration which contains 10 options namely, APPEND, CREATE, CREATE_NEW, DELETE_ON_CLOSE, DSYNC, READ, SPARSE, SYNC, TRUNCATE_EXISTING, WRITE.

You can invoke this method by passing the path of the file, byte array containing the data to be appended and, the option StandardOpenOption.APPEND.

Example

Following Java program has an array storing 5 integer values, we are letting the user choose two elements from the array (indices of the elements) and performing division between them. We are wrapping this code in a try block with three catch blocks catching ArithmeticException, InputMismatchException and, ArrayIndexOutOfBoundsException. In each of them, we are invoking the writeToFile() method.

This method accepts an exception object and appends it to a file using the write() method of the Files class.

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\n"+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);
      }
   }
}

Output1

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

Output2

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

Output3

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
raja
Published on 12-Sep-2019 09:45:25
Advertisements