Using append( ) method of FileWriter I/O Class, we can append our text to the existing text written by the write( ) method in the file.
append( ) method can directly append our text to the existing text (written by write( ) method) of the file as shown in the below example -
Example -
File file1 = new File("def.txt");
FileWriter fw = new FileWriter(file1);
fw.write("How are you doing today?"); //Text written by the write( ) method into file
fw.append(" I am doing good."); //Appends the text to the text written by write( ) method
Output (Inside text file) -
How are you doing today? I am doing good
Lets implement this on Eclipse IDE -
1. Launch Eclipse IDE, create a new Java Class 'AppendMethodDemo.java' with main( ) method in the existing Java Project 'Project 51' as shown below -
2. Go to our Project Workspace, create an empty file 'def.txt' as shown below -
3. In Eclipse IDE -> 'AppendMethodDemo.java' Class, create a File Class object for the file 'def.txt' created in our project workspace as shown below (Resolve import error) -
4. Create a FileWriter Class object for the above file file1 as shown below (Resolve import error) -
5. View the error and select 'Add throws declaration' option from the error message (I am adding throws for explanation purpose, in reality we should add try/catch to resolve the error) -
6. Observe that IOException Class got added to the method declaration and the error got resolved as shown below -
7. Use write( ) method of FileWriter Class to write the text 'How are you doing today?' into the text file 'def.txt' as shown below -
8. Save & Run the program and observe that the text written by the write( ) method is displayed in the 'def.txt' file as shown below -
8. Now use the append( ) method of FileWriter Class to append the text ' I am doing good.' to the existing text of the 'def.txt' file that is written by write( ) method as shown below -
9. Close the FileWriter object fw to resolve the warning message as shown below -
10. Save & Run the Java Class 'AppendMethodDemo.java' and observe that ' I am doing good.' text got append to the text written by the write( ) method in 'def.txt' file in our project workspace as shown below -
append( ) method appends the new text to the text that was written by the write( ) method. Dont use append( ) method when to want to append your text to the manually written text, as the append( ) will remove the manually written text from the file and add the text specified inside the append( ) method. Hence use append( ) method only to append new text to the existing text that was written by the write( ) method.
Please comment below to feedback or ask questions.
No comments:
Post a Comment