60 likes | 141 Views
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).
E N D
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?
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.
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.
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”);
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