Java

TOPIC I02 – WRITING TO A FILE

 

 

LESSON NOTE

 

 

INTRO

 

Again, this is quite easy.  All you need to do is start with the template and make changes as needed.

 

STEPS FOR WRITING TO A FILE

 

These are the steps that you would use in any language:

 

Step 1 – Open the file.

 

This will create the file that you specify.  Careful!  If the file exists, it will be overwritten.

 

Again, java has a specially class that knows how to communicate with files.

 

Step 2 – Write the data.

 

This can be done in a loop or as a single command. 

 

It should be noted that the writing is done into a buffer.  Once the buffer is full, it is transferred to the file.  This is done behind the scenes.

 

Step 3 – Close the file.

 

This step makes the file available for editing by other programs.  However, it also flushes the buffer so that all data is in the file.  So, if you forget to close the file, you might miss some data at the end!

 

EXAMPLE PROGRAM

 

TEXT FILE WITH CODE

 

Click here to get the code in a text file.

 

THINGS TO CHANGE FOR YOUR PROGRAM

 

When you want to create your program, here is what you have to change:

 

  • You need to change the file name to whatever file name you want.  Careful not to overwrite something important!
  • You need to change the code inside step 2 so that the program writes what you want it to write.

 

 

HOW TO APPEND TO A FILE INSTEAD OF OVERWRITE IT?

 

Using the code above, when you write to a text file, you overwrite (erase) anything that was in the text file when you opened it.

 

To write to the end of the text file instead, you simply need to add a parameter in the constructor call to FileWriter.  See the code below:

 

SEEING A NEW TEXT FILE

 

If you run your program in Eclipse and you do not see a new text file appear, you simply need to right click on your project name and choose REFRESH.  Then you should see your new text file appear.