import java.io.FileNotFoundException;
import java.io.PrintStream;
class WriteOK {
public static void main(String args[>)throws FileNotFoundException {
PrintStream diskWriter = new PrintStream(new File("approval.txt"));
diskWriter.print ('O');
diskWriter.println('K');
diskWriter.close();
}
Here’s the sequence of events, from the start to the end of the experiment:
- Before you run the code, the computer’s hard drive has no
approval.txt
file.That’s okay. Every experiment has to start somewhere.
- Run the code above.
The call to new
PrintStream
creates a file namedapproval.txt
. Initially, the newapproval.txt
file contains no characters. Later in the code, calls toprint
andprintln
put characters in the file. So, after running the code, theapproval.txt
file contains two letters: the lettersOK
. - Run the code a second time.
At this point, you could imagine seeing
OKOK
in theapproval.txt
file. But that’s not what you see above. After running the code twice, theapproval.txt
file contains just oneOK
. Here’s why:- The call to
new PrintStream
in the code deletes the existingapproval.txt
file. The call creates a new, emptyapproval.txt
file. - After a
new approval.txt
file is created, theprint
method call drops the letterO
into the new file. - The
println
method call adds the letterK
to the sameapproval.txt
file.
- The call to
approval.txt
file is already on the hard drive. Then the program adds data to a newly created approval.txt
file.
Where’s my file?
Create an Eclipse project containing the following code:import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
class ReadAndWrite {
public static void main(String args[>) throws FileNotFoundException {
<strong> Scanner diskScanner = new Scanner(new File("data.txt"));</strong>
<strong> PrintStream diskWriter = new PrintStream("data.txt");</strong>
diskWriter.println("Hello");
System.out.println(diskScanner.next());
diskScanner.close();
diskWriter.close();
}
}
When you run the code, you see an error message in Eclipse's Console view. Why?
Write and then read
Modify the code from the where's-my-file experiment so that the code>PrintStream diskWriter declaration comes before the ScannerdiskScanner
declaration.When you run the code, the word Hello
should appear in Eclipse's Console view. After running the code, check to make sure that your Eclipse project contains a file named data.txt
.