Home > Back-end >  Reading a part of an inputStream and converting to list of bytes
Reading a part of an inputStream and converting to list of bytes

Time:11-06

I'm trying to impelment a method which recieves an InputStream from a txt file that has a certain string wrapped in quotation marks. The string should then be returned as a list of bytes.

public static List<Byte> getQuoted(InputStream in) throws IOException {

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            boolean quoteWasFound = false;
            int r;

            // First go through the input stream until reaching first quotation mark.
            while ((r = reader.read()) != -1) {
                in.readNBytes(2);
                if ((char) r == '"') {
                    quoteWasFound = true;
                    break;
                }
            } 

            List<Byte> byteList = new ArrayList<>();

            // If quote mark was found in previous loop, start adding the bytes from the
            // inputstream (2 at a time) until one of two thing happen: another quotation
            // mark was found OR reached end of input stream.
            while (quoteWasFound && (r = reader.read()) != -1) {
                if ((char) r == '"')
                    break;
                for (int i = 0; i <= 1; i  ) {
                    byteList.add((byte) in.read());
                }
            } 

            if (byteList.isEmpty())
                return null;
            else
                return byteList;
        } catch (IOException e) {
            throw new IOException();
        } 
    }

When I ran the code I got this output:

[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]

And this is what I'm expecting:

[114, 101, 116, 117, 114, 110, 32, 116, 104, 105, 115, 32, 115, 117, 98, 115, 116, 114, 105, 110, 103]

I'm guessing there's a problem with the way I'm converting from int to char or from int to byte, but I can't figure out what's causing it.

Thanks in advance to all who share their wisdom!

CodePudding user response:

Mixing a Reader and an Input stream on the same stream is what's causing the issue. You'll have to pick one or the other, not both.

  • Related