1 / 6

Appending Data and Selecting a File’s Location

Appending Data and Selecting a File’s Location. When a PrintWriter object is created for a particular file (like “crow.txt”), its constructor will write over that file if it currently exists. (All the data in “crow.txt” will be deleted).

Download Presentation

Appending Data and Selecting a File’s Location

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Appending DataandSelecting a File’s Location

  2. When a PrintWriter object is created for a particular file (like “crow.txt”), its constructor will write over that file if it currently exists. (All the data in “crow.txt” will be deleted). • What if we want to write to add more data to a file after it had been closed?

  3. Append: • Writing new data at the end of file. • FileWriter class: • Allows us to append data to a file. • Ex: FileWriter fwriter = new FileWriter(“crow.txt”, true); The file we are opening. A FileWriter object named “fwriter” is created that opens (not creates) the file. You have to type “true” here.

  4. You must still use a PrintWriter object to write data to the file after you open it with the FileWriter object. FileWriter fwriter = new FileWriter(“crow.txt", true); PrintWriter outputFile = new PrintWriter(fwriter); outputFile.println(“Hello!"); outputFile.close(); Open the file with the FileWriter object, and then reference that with the PrintWriter object.

  5. Specifying the File Location: • You can specify a file’s location with its path and file name. • Java requires you enter 2 backslashes for a folder or directory OR 1 forward slash. • Ex: PrintWriter outputFile = new PrintWriter(“F:\\java\\crowtext.txt”); OR PrintWriter outputFile = new PrintWriter(“F:/java/crowtext.txt”);

  6. When a user is entering the file location in a program, they DO NOT need to provide the double backslashes. • Ex: >Enter file location: F:\java\crow.txt >Enter file location: F:\\java\\crow.txt CORRECT NOT CORRECT

More Related