Java BufferedReader for zero-terminated strings

你离开我真会死。 提交于 2019-12-13 16:51:16

问题


I need to read zero-terminated strings from InputStream in Java.

Is there similar to BufferedReader.readLine() method for reading zero-terminated strings?


回答1:


No. Java doesn't recognise a zero-terminated string as such. You'll have to read the InputStream and look for a 0 byte.

Note that this doesn't address the issue of character-encoding. The InputStream will give you the stream of bytes, and you'll then have to encode to characters via a Reader. If you have a multi-byte character encoding then the issue becomes more complex.




回答2:


package com;

import java.io.*;
import java.util.Scanner;

public class AAA {

    private static final String ENCODING = "UTF-8";

    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        bOut.write("the first line".getBytes(ENCODING));
        bOut.write(0);
        bOut.write("the second line\r\n (long one)".getBytes(ENCODING));
        bOut.write(0);
        bOut.write("the third line".getBytes(ENCODING));
        printLines(new ByteArrayInputStream(bOut.toByteArray()));
    }

    public static void printLines(InputStream in) {
        Scanner scanner = new Scanner(in, ENCODING);
        scanner.useDelimiter("\u0000");
        while (scanner.hasNext()) {
            System.out.println(scanner.next());
            System.out.println("--------------------------------");
        }
    }
}



回答3:


you will also need to understand what is that "zero" means . input/output streams deal with bytes whereas readers/writers deal with characters. if you want to match against a zero character then byte to char conversion encoding will come into play.




回答4:


You could create a method similar to the one below. Create a BufferedReader from an InputStream. The BufferedReader is passed by reference so it will retain state. It could easily be stored in an instance variable as well.

public String readLine(BufferedReader buff) throws IOException{
    int c = buff.read();
    // if EOF
    if (c == -1){
        return null;
    }
    StringBuilder builder = new StringBuilder("");
    // Check if new line or EOF
    while (c != -1 && c != 0){
        builder.append((char) c);
        c = buff.read();
    }
    return builder.toString();
}

....

String line = reader.readLine(buff);
while (line != null)
{
System.out.println(line);
line = reader.readLine(someBufferedReader);

}


来源:https://stackoverflow.com/questions/1686789/java-bufferedreader-for-zero-terminated-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!