1

I am trying to read a single line which is about 2 million characters long from the standard input using the following code:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
s = in.readLine();

For the aforementioned input, the s = in.readLine(); line takes over 30 minutes to execute.

Is there a faster way of reading this input?

Kirill Kulakov
  • 10,035
  • 9
  • 50
  • 67

1 Answers1

1

Don't try to read line by line but try to read a buffer of characters instead

Try something like this

BufferedInputStream in = null;
try {
    in = new BufferedInputStream(new FileInputStream("your-file"));

    byte[] data = new byte[1024];
    int count = 0;

    while ((count = in.read(data)) != -1) {
      // do what you want - save to other file, use a StringBuilder, it's your choice
    }
} catch (IOException ex1) {
  // Handle if something goes wrong
} finally {
    if (in != null) {
      try {
        in.close();
      } catch (IOException ) {
        // Handle if something goes wrong
      }
    }
}
Kiril Aleksandrov
  • 2,601
  • 20
  • 27