Streams and File I/O

Appending to A Text File

Page 1 of 1

1 Replies - 369 Views - Last Post: 19 April 2010 - 10:00 PM Rate Topic: -----

#1 mellzdopetar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 24-January 10

Streams and File I/O

Posted 19 April 2010 - 09:54 PM

Hey Guys,

So my professor has given me these lines of code:

import java.io.PrintWriter; // *********** SAME PROGRAM WRITE TO A TEXT FILE *****
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TextFileOutputDemo {
public static void main (String [] args) {
String fileName = "out.txt"; // name of file we will create
PrintWriter prWriter; // this object knows how to write to a file.
String line = new String (" "); // capture user input to write to file.
try {
prWriter = new PrintWriter (fileName);
System.out.println ("Enter three lines of text:");
Scanner keyboard = new Scanner (System.in);
for (int count = 1 ; count <= 3 ; count++) {
line = keyboard.nextLine ();
prWriter.println (count + " " + line);
} // for
prWriter.close ();
System.out.println ("Those lines were written to " + fileName);
} // try
catch (FileNotFoundException e) {
System.out.println ("Error opening the file " + fileName);
} // catch
} // main
} // class


And then she explains appending to a text file by using a constructor. However i have no idea what it means to open a file to 'append', nor do i understand how to do it. Any advice? Ive also attached the class ppt lesson.

Melissa

Attached File(s)



Is This A Good Question/Topic? 0
  • +

Replies To: Streams and File I/O

#2 chls89  Icon User is offline

  • New D.I.C Head

Reputation: 12
  • View blog
  • Posts: 47
  • Joined: 19-September 09

Re: Streams and File I/O

Posted 19 April 2010 - 10:00 PM

Using FileWriter as an example, it has many constructors. For example, one constructor is
FileWriter(File fileName);

But the useful constructor to you would be:
FileWriter(File fileName, boolean append);

Where if append is true, the file will be opened for appending.

This post has been edited by chls89: 19 April 2010 - 10:01 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1