Search code examples
javabyteinputstreamquotes

Reading from InputStream until double quotation marks


Need help reading from InputStream to a list of bytes until quotation marks. The problem is, InputStream reads bytes and I'm not sure how to stop it reading when it reaches quotation marks ... I thought about something like this:

public static List<Byte> getQuoted(InputStream in) throws IOException {
    int c;
    LinkedList<Byte> myList = new LinkedList<>();
    try {
    while ((in.read()) != "\"") {   ?????
        list.add(c)
    .....

The while condition is a problem, of course the quotation marks are String while int is expected.


Solution

  • "\"" is a String. If you want just the character representation of ", use '"' instead.

    Note that your code will not work as you expect if your file is not in ASCII format (and the behaviour will be inconsistent between different character sets) (it does of course depend what you expect).

    If in ASCII, each character will take up a single byte in the file and InputStream::read() reads a single byte (thus a single ASCII character) so everything will work fine.

    If in a character set that takes up more than 1 byte per character (e.g. Unicode), each read will read less than a single character and your code will probably not work as expected.

    Reader::read() (and using Character rather than Byte) is advised since it will read a character, not just a byte.

    Also, you're missing an assignment:

    while ((in.read()) != '"')
    

    should be

    while ((c = in.read()) != '"')