Using BufferedReader and PrintWriter - nus-cs2030/2021-s1 GitHub Wiki
Hi all! Here is a quick guide on how to use BufferedReader and PrintWriter to handle IO in Java. You may find this very useful if you are taking CS2040/S in the near future.
Why not use Scanner / System.out?
Scanner is the common way to take in user input in CS2030 and has many useful functions (e.g. nextInt(), nextDouble(), etc). However, its actually a pretty slow way of taking in input. Similarly, System.out.print()/println()/printf() takes a lot of time if it is called repeatedly.
Using BufferedReader to handle inputs and PrintWriter to handle outputs can greatly speed up your program, although they are slightly more complicated to use. This time-saving can help you pass test cases where exceeding time limit is a concern.
BufferedReader
BufferedReader(BR) provides a much faster way to take in user input.
- First, remember to import BR using:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException;
- Initalize your BR using:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- BR gives less flexibility than Scanner. The most useful method is
readLine()
which reads a whole line of input, similar to Scanner'snextLine()
. You may refer to https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/BufferedReader.html for more methods. - BR's methods, including
readLine()
,throws IOException
. Hence, in the method where you make use of BR, you should either handle theIOException
or declare that your method alsothrows IOException
.
PrintWriter
PrintWriter(PW) provides a much faster way to write output. Unlike System.out
which prints immediately, PW delays printing until flush()
or close()
is called, hence avoiding switching between printing and computation to save time.
- First, remember to import PW using:
import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.OutputStreamWriter;
- Initalize your PW using:
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
- Useful methods:
print(String str)
-> prints str,println(String str)
-> prints str, followed by a newline character. Use these methods similar to how you would use the corresponding methods ofSystem.out
. You may refer to https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/PrintWriter.html for more methods. - Always call
flush()
orclose()
on the PW before exiting the program, or the output may not be printed.flush()
flushes the buffer and prints the contents of the writer to screen, whileclose()
callsflush()
and then closes the PW, which cannot be used again.