Skip to content

Using BufferedReader and PrintWriter

Shuyang0 edited this page Nov 30, 2020 · 1 revision

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's nextLine(). 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 the IOException or declare that your method also throws 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 of System.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() or close() 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, while close() calls flush() and then closes the PW, which cannot be used again.
Clone this wiki locally