KingSweeney
KingSweeney

Reputation: 11

Optimizing BufferedReader for large input in java

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?

Upvotes: 1

Views: 681

Answers (1)

Kiril Aleksandrov
Kiril Aleksandrov

Reputation: 2591

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
      }
    }
}

Upvotes: 1

Related Questions