Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.


+17 votes

For a file print stream, what is the parameter that we have to use to call on the method that is printing the lines of the file?

asked in CSC211_Winter2018 by (1 point)

1 Answer

+7 votes

You can reference PrintStream objects in the same manner you have referenced Console objects in the past when you printed variables to the console. Keep your file name in mind; if it doesn't exist, Java will make a new file with that name, and if it does exist, it will overwrite the existing file. Try not to have your program read from and print to the same file, because there's a chance it will become corrupted when you're reading from a file that is being simultaneously overwritten.

To print something to a file, call it as such:

PrintStream output = new PrintStream(new File("output.txt"));
output.println("This is a line of text.");
for (int i = 1; i <= 3; i++) {

// prints the following to output.txt:
// This is a line of text.
// 123

answered by (1 point)