Java Exercises: Append text to an existing file
Java Input-Output: Exercise-16 with Solution
Write a Java program to append text to an existing file.
Sample Solution:
Java Code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
public class Exercise16 {
public static void main(String a[]){
StringBuilder sb = new StringBuilder();
String strLine = "";
try
{
String filename= "/home/students/myfile.txt";
FileWriter fw = new FileWriter(filename,true);
//appends the string to the file
fw.write("Java Exercises\n");
fw.close();
BufferedReader br = new BufferedReader(new FileReader("/home/students/myfile.txt"));
//read the file content
while (strLine != null)
{
sb.append(strLine);
sb.append(System.lineSeparator());
strLine = br.readLine();
System.out.println(strLine);
}
br.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
}
Sample Output:
Python Exercises Java Exercises null
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to write and read a plain text file.
Next: Write a Java program to read first 3 lines from a file.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework