Saturday, April 25, 2009

Writing and Appending

Hi everyone,
When you are programming, you will need to store data on files. some times you want to discard all the contents of the file and write all the data right from the beginning, and other times you want to add just a line to the data in file.

The first type is called writing while the second one is named appending. The default when you create a FileWriter in JAVA it will overwrite all the data in the file.


FileWriter writer = new FileWriter("sample.txt");
writer.write("Trying writing in file");
writer.close();


If you run this code, the FileWriter "writer" will delete all lines in "sample.txt" and write from the beginning of the file. If the file doesn't exist it will be created and the "writer" will write in it.
Note:
1 - You must always close any input or output streams in order to perform appropriate operations.
2 - You will have to import java packages:

import java.io.FileWriter;
import java.io.IOException;

3 - You will have to throw or try and catch IOException.




Let's see the appending.
Try this code


FileWriter writer = new FileWriter("sample.txt");
writer.write("The first line was deleted");
writer.close();


You will find only one sentence "The first line was deleted", the other sentence we wrote on the first coding doesn't exist any more. Sometimes there is no problem with that, but what if you want to add the new line with out deleting the already written one ?

To answer the question try this thing:


FileWriter writer = new FileWriter("sample.txt", true);
writer.write("\nThe first line was not deleted");
writer.close();


The true that we added to the constructor means that we want the FileWriter to append the new data to the existing data.

These Images will show every thing


Writing in the file:




Overwriting the data in the file:




Appending to the file:








Well that's all for now, See soon isa.

2 comments:

  1. Thanks Khaled For your help , i already knew it but anyway thanks for ur Efforts and Mabrook 3la el Bolg , We ya reet neshoof ur comments here http://www.mahfouzcorponline.tk/

    ReplyDelete
  2. Thanks for you that you give me your time and read it.
    I will check your blog isa

    ReplyDelete