
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Java Program to Append Text to an Existing File
- How to add a JSON string to an existing JSON file in Java?
- Append to an existing file stored in SD Card connected to Arduino
- How to create a duplicate file of an existing file using Python?
- C++ program to append content of one text file to another
- How to append data to a file in Java?
- How to append a second list to an existing list in C#?
- How to add a title to an existing line border in Java?
- How to add columns to an existing MySQL table?
- How to add a new column to an existing table using JDBC API?
- Add alpha to an existing Matplotlib colormap
- How to add current date to an existing MySQL table?
- How to add column to an existing table in PostgreSQL?
- How to add an attribute to the XML file using Powershell?
- How to append data into a CSV file using PowerShell?