- Java Basic Programs
- Java Programming Examples
- Java Print Hello World
- Java Get Input from User
- Java Print Integer
- Java Add two Numbers
- Java Check Even or Odd
- Java Check Prime or Not
- Java Check Alphabet or Not
- Java Check Vowel or Not
- Check Reverse equal Original
- Java Fahrenheit to Celsius
- Java Celsius to Fahrenheit
- Java Perfect Number Program
- Java Find Quotient Remainder
- Java Days to Seconds
- Java Count Digits in Number
- Java Binary Number Addition
- Java Discount Program
- Java Compute Courier Charge
- Java Find Telephone Bill
- Java Print ASCII Values
- Java Check Palindrome or Not
- Java Check Armstrong or Not
- Generate Armstrong Numbers
- Add two Numbers using Pointers
- Java Mathematical Programs
- Add Subtract Multiply & Divide
- Java Make Calculator
- Java Add Digits of Number
- Java Check Leap Year or Not
- Java Check Divisibility
- Java Find Simple Interest
- Java Find Compound Interest
- Java Print Fibonacci Series
- Java Find nCr nPr
- Calculate Average & Percentage
- Java Calculate Arithmetic Mean
- Java Calculate Student Grade
- Java Print Table of Number
- Java Print Prime Numbers
- Java Add n Numbers
- Java Interchange two Numbers
- Java Reverse Numbers
- Java Swap two Numbers
- Count Positive Negative & Zero
- Find Largest of two Numbers
- Find Largest of three Numbers
- Java Find Factorial of Number
- Java Find HCF & LCM
- Area & Perimeter of Square
- Area & Perimeter of Rectangle
- Area & Circumference of Circle
- Java Conversion Programs
- Java Decimal to Binary
- Java Decimal to Octal
- Java Decimal to Hexadecimal
- Java Binary to Decimal
- Java Binary to Octal
- Java Binary to Hexadecimal
- Java Octal to Decimal
- Java Octal to Binary
- Java Octal to Hexadecimal
- Java Hexadecimal to Decimal
- Java Hexadecimal to Binary
- Java Hexadecimal to Octal
- Java Pattern Programs
- Java Pattern of Stars
- Java Pattern of Alphabets
- Java Pattern of Numbers
- Java Pyramid of Stars
- Java Pyramid of Alphabets
- Java Pyramid of Numbers
- Java Print Diamond Pattern
- Java Print Floyd Triangle
- Java Print Pascal Triangle
- Java Array Programs
- One Dimensional Array Program
- Java Linear Search
- Java Binary Search
- Find Largest Element in Array
- Find Smallest Element in Array
- Java Reverse Array
- Insert Element in Array
- Delete Element from Array
- Java Merge two Array
- Java Bubble Sort
- Java Selection Sort
- Java Insertion Sort
- Java Find Common Elements
- Java Count Even/Odd Number
- Two Dimensional Array Program
- Java Add two Matrices
- Java Subtract two Matrices
- Java Transpose Matrix
- Multiply two Matrices
- Three Dimension Array Program
- Java String Programs
- Java Print String
- Find Length of String
- Java Compare two String
- Java Copy String
- Java Concatenate String
- Java Reverse String
- Delete Vowels from String
- Delete Words from Sentence
- Find Occurrence of a Character
- Java Find Occurrence of a Word
- Occurrence of Each Character
- Java Occurrence of Each Word
- Java Count Repeated Characters
- Java Count Repeated Words
- Java Capitalize Each Word
- Java Count Vowels/Consonants
- Java Extract Numbers
- Java Count Word in String
- Remove Spaces from String
- Java Sort a String
- Java Uppercase to Lowercase
- Java Lowercase to Uppercase
- Java Swap two Strings
- Java Check Anagram or Not
- Java Check Balance Parentheses
- Java Check Password Strength
- Java File Programs
- Java Read File
- Java Write to File
- Read & Display File Content
- Java Copy File
- Java Append Text to File
- Java Merge two File
- List files in Directory
- Java Delete File
- Java Miscellaneous Programs
- Generate Random Numbers
- Java Print Time & Date
- Java Get IP Address
- Java Shutdown Computer
- Java Programming Tutorial
- Java Tutorial
Java Program to Append Text to an Existing File
I've created this article to cover some programs in Java to append some text or string to an existing file. Let's start with very basic one.
What to Do before Program ?
Since the program given below is used to append some new text to an existing file, therefore we must have a file say fresherearth.txt available in the current directory. Therefore I'm going to create a file with some text.
Now I've create the file named fresherearth.txt with its text as I'm the old content. and saved the file inside the current directory (the directory where the Java program or source code is saved). Here is the snapshot of the opened file:
Now let's move on, and create a Java program that appends some new text to this newly created file.
Appending Text to a File in Java
The question is, write a Java program to append text to an existing file. The program given below is the answer to this question. This is the very basic version of the program.
import java.io.*; public class fresherearth { public static void main(String[] args) { try { FileWriter fw = new FileWriter("fresherearth.txt", true); fw.write("\nI'm the new content."); fw.close(); System.out.println("The content is successfully appended to the file."); } catch(IOException ioe) { System.out.print("\nSomething went wrong!"); } } }
If you run or execute the above program, then here is the sample output you'll see on your output screen:
And after executing the above program, if you open and see the file fresherearth.txt, then you'll see the text say I'm the new content. will available in the file without removing the previous. Here is the new snapshot of the same file:
In above program, I've used \n before the text that is going to append, to append the text from new line. And the true as second parameter of FileWriter, is used to enable appending mode. If we remove the second parameter, then the previous text of the file will get removed and the new text will get written, instead of appending.
The following statement:
FileWriter fw = new FileWriter("fresherearth.txt", true);
is enclosed inside the try block to catch the error or exception raised in some cases such as file doesn't exist, write operation is not allowed etc. Rest of the things are I thing self-understandable. Now let's move on to modify the above program.
Java Append Text to File - Complete Version
This is the complete version of the file append operation in Java. This program allows user to perform the operation based on his/her requirement. Multiple line of texts can also be appended to the file using this program. Do concentrate on the program to get some extra knowledge on the topic.
import java.io.*; import java.util.Scanner; public class fresherearth { public static void main(String[] args) { String filename, line="", content=""; char ch; int totLine, i; Scanner scan = new Scanner(System.in); System.out.print("Enter the Name of File: "); filename = scan.nextLine(); while(true) { try { FileReader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr); System.out.println("\n----Content of File----"); while((line = br.readLine()) != null) { System.out.println(line); } br.close(); System.out.print("\nWant to append the text (y/n) ? "); ch = scan.next().charAt(0); if(ch=='y') { System.out.println("\n1. Append Single Line of Text."); System.out.println("2. Append Multiple Line of Text."); System.out.print("Enter Your Choice (1 or 2): "); ch = scan.next().charAt(0); if(ch=='1') { Scanner s = new Scanner(System.in); System.out.print("\nEnter the Text: "); line = s.nextLine(); try { FileWriter fw = new FileWriter(filename, true); fw.write("\n"); fw.write(line); fw.close(); System.out.println("\nThe content is successfully appended to the file."); } catch(IOException ioe) { System.out.print("\nSomething went wrong!"); } } else if(ch=='2') { Scanner s = new Scanner(System.in); System.out.print("\nHow many lines to write ? "); totLine = s.nextInt(); System.out.print("Enter " +totLine+ " lines of text: "); for(i=0; i<(totLine+1); i++) { line = s.nextLine(); if((i+1)<(totLine+1)) line = line + '\n'; content = content + line; } try { FileWriter fw = new FileWriter(filename, true); fw.write(content); fw.close(); System.out.println("\nThe content is successfully appended to the file."); } catch(IOException ioe) { System.out.print("\nSomething went wrong!"); } } else { System.out.println("\nInvaid Choice!"); break; } System.out.print("\nWant to see the new content (y/s) ? "); ch = scan.next().charAt(0); if(ch!='y') break; } else { break; } } catch(IOException ioe) { System.out.println("\nFile Not Found!"); } } } }
Here is its sample run with following user inputs:
- fresherearth.txt as the name of file to operate
- y as choice to see the content of this file
- 1 as choice to append the single line of text to the file
- I'm another new content. as text to append
- y as choice to see the new content of same file
The snapshot given below shows the sample run with these inputs:
Since the whole, main part of the program, is enclosed within a while loop with its condition true. Therefore the execution of program continues, until you enter n or anything other than y to exit from the loop. Here is the continued sample run with some other inputs:
Since I've supplied n (not 'y') as choice, not to further append the text to the file, therefore the program execution discontinues.
« Previous Program Next Program »