












Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!













File output is very similar to terminal output, except we have to open and close files To create a stream between a variable name and file name: Type Variable name PrintWriter constructor Another constructor File nameDocsity.com
After you have opened a file (stream), you can then write to it This is done in an almost identical manner with println() (or print() or printf()) Terminal: File:
You need to import PrintWriter and FileOutputStream from java.io You can also simply import everything from java.io by doing: (See: HelloWorldFile.java)
Whenever you open a file (for write or read), a checked exception is thrown named java.io.FileNotFoundException This means you have to catch it! (See: HelloWorldFileCorrected.java)
What happens if I run HelloWorldFile multiple times? Open file and override: Open file and append: (See: HelloWorldFileAppend.java) Docsity.com
Open: Read: Close: FileInputStream not FileOutputStream (See: HelloWorldReader.java)
What would happen if I tried to have two nextLine() calls in HelloWorldReader? This would in fact crash the program, very similar to if you used nextInt() on a String There is no way for Scanner to tell if it reached the end of the file (EOF)
BufferedReader can also read from a file To open a file: FileReader not FileInputStream However, BufferedReader only has 2 methods: read() - reads a single character readLine() - reads a line, like nextLine()
If the end of file is reached in BufferedReader, then read() will return - (readLine() will return null) Since read() only reads a single character, you have to put together Strings/ints manually (See: BufferedReaderMaxBad) (See: BufferedReaderMaxGood)