Java Append Data to File
When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data inserted.
However, there are some situations where appending data (a message) to the next line of the file is necessary, such as when logging exceptions together into the file without using logger frameworks.
Files classes of a java. nio package can be used to accomplish this. This class offers a write() function that accepts
- A file is represented by a Path class object.
- a byte array containing the file's data
One of the members of the StandardOpenOption enumeration, which has 10 options, namely, create, create new, append, delete, on close, read, sync, spare, truncate existing, and write, dsynccan be sent as a value to an OpenOption (interface) type variable.
The file location, byte array holding the data to be appended, and the option StandardOpenOption.APPEND must be passed when calling this method.
Example
In the Java application below, we are allowing the user to select two components from the array (based on their indices) and execute division between them. The array contains five integer values. ArithmeticException, InputMismatchException, and ArrayIndexOutOfBoundsException are caught by three catch blocks that are placed around this code in a try block. We are calling the writeToFile() method in each one of them.
The write() function of the Files class is used in this method to attach an exception object to a file.
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 was recorded in your file.");
}
public static void main(String [] args) throws IOException {
Scanner sc = new Scanner(System.in);
int[] arr = {1, 12, 20, 30, 1, 0};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose the numerator as well as the denominator (not 0) from the above-mentioned array (enter locations 0 to 5)");
try {
int x = sc.nextInt();
int y = sc.nextInt();
int result = (arr[x])/(arr[y]);
System.out.println("Result of "+arr[x]+"/"+arr[y]+": "+result);
}catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Warning: You've selected a location that isn't part of 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);
}
}
}
Append to File in Java
Using the classes shown below, we can append to files in Java.
- Java file append employing FileWriter
- Java uses BufferedWriter to append material to an existing file.
- Java program to add text to a file using PrintWriter.
- Using FileOutputStream, appenda new line to a file in Java.
Java File Append Employing FileWriter
Using the write() function of the Files class, we may create a new file. Internally, the write() function writes a byte array further into a file using an OutputStream.
Use StandardOpenOption to add content to a file that already exists.While creating the material, use APPEND.
File file = new File("append.text");
FileWriter f = new FileWriter(file, true);
f.write("data");
f.close();
Java uses BufferedWriter to Append Material to an Existing File.
To reduce IO operations and boost efficiency, BufferedWriter buffers all data in an inner byte array before writing to the file.
Launch the writer using append mode and enter the true value for the second argument to attach a string to an existing file.
File file = new File("append.text");
FileWriter f = new FileWriter(file, true);
BufferWriter b = new BufferWriter(f);
b.write("data");
b.close();
f.close();
Using PrintWriter, Append Text to a File in Java.
The PrintWriter can be used to write formatting to a file. Because PrintWriter implements every print() method in PrintStream, we can use any format that System.out.println() commands support.
Launch the writer using append mode by giving the second option as true to add material to an existing file.
File file = new File("append.text");
FileWriter f = new FileWriter(file, true);
BufferWriter b = new BufferWriter(f);
PrintWriter p = new PrintWriter(b);
p.println("data");
p.close();
b.close();
f.close();
Using FileOutputStream, Append a New Line to a File in Java.
To write binary data into a file, use FileOutputStream. FileOutputStream is designed for outputting streams of uncompressed bytes, such as image data. Think about using FileWriter to write streams of characters.
Create FileOutputStream in append fashion by giving the second option as true to append material to an existing file.
OutputStreamos = new FileOutputStream(new File("append.txt"), true);
os.write("data".getBytes(), 0, "data".length());
os.close();