Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BufferedReader for zero-terminated strings

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

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

like image 656
Domas Avatar asked May 30 '26 11:05

Domas


1 Answers

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("--------------------------------");
        }
    }
}
like image 59
denis.zhdanov Avatar answered Jun 01 '26 01:06

denis.zhdanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!