1

readLine() returns a String, but what I need are the ASCII characters of the characters of each string on each line.

E.g.

ABCDE XYZ

I need the ASCII characters of A, B, C, D, E, and also X, Y, Z, but separately. Currently, I'm using BufferedReader's readLine method, then loop through the length of the string and using String.charAt() to retrieve the character at each position. It's then trivial to convert characters to bytes.

I figured it must be expensive to create strings from bytes, then convert back into bytes. I tried writing my own solution using FileChannel:

        FileChannel f = FileChannel.open(Paths.get("file.txt"));
        ByteBuffer buffer = ByteBuffer.allocate(10000);
        bytesRead = 0;
        byte[] chunk = new byte[10000];

        while (bytesRead != -1) {
            bytesRead = f.read(buffer);
            buffer.flip();

            while (buffer.hasRemaining()) {
                buffer.get(chunk, 0, bytesRead);
                processChunk(chunk);
            }

            buffer.clear();
        }

I don't know why but this turned out to be slower than BufferedReader's readLine() method.

I found this answer: Why is the performance of BufferedReader so much worse than BufferedInputStream? and I was wondering if BufferedInputStream could be of help to me.

Speed is of utmost priority for this!

RAGHHURAAMM
  • 1,099
  • 7
  • 15
Fabian
  • 397
  • 1
  • 4
  • 12
  • I’m not sure what “ASCII characters of A, B, C, D, E” means, since ABCDE are already ASCII characters. Perhaps you meant the ASCII *codes* of those characters, as byte values? Perhaps you should just read them from a BufferedInputStream? – VGR Oct 18 '18 at 03:57
  • Yes sorry, I meant the numeric codes. – Fabian Oct 18 '18 at 04:46
  • @VGR So I tried using a BIS and I'm getting TLE on my assignment submission page (online grader). https://repl.it/repls/FloralwhiteIdenticalAtoms It seems that BufferedReader's readLine() is still way way faster for reading lines. Is there a way to read a line (until a newline character) without first building a string from it, because ultimately I want the bytes, and not the string representation? – Fabian Oct 18 '18 at 05:35
  • Don”t use Strings at all. Just read bytes one by one from the InputStream until you get a byte whose value is -1 or 10 (the codepoint value of `\n`). – VGR Oct 18 '18 at 12:17

0 Answers0