难以将字符串转换为字节[]

时间:2021-10-15 22:25:27
public static Runnable reader() throws IOException {
    Log.e("Communication", "reader");
    din = new DataInputStream(sock.getInputStream());
    brdr = new BufferedReader(new InputStreamReader(din), 300);
    boolean done = false;
    while (!done) {
        try {
            char[] buffer = new char[200];
            int anzahlZeichen = brdr.read(buffer, 0, 200);
            String nachricht = new String(buffer, 0, anzahlZeichen);
            byte[] in = nachricht.getBytes("ISO-8859-1");
            for (int counter = 0; counter < nachricht.length(); counter++) {
                System.out.println(in);
            }
            if (nachricht != null)
                answer();
            System.out.println(nachricht);

        } catch (IOException ioe) {
            done = true;
        }
    }

    return null;
}

i want to convert the String nachricht to the Byte[] in but i dont get it. Could anyone help pls? I am just receiving Numbers, no words or letters. Another method is welcome, too. All i get at System.out.println(nachricht)is seven times[B@41c04778 but i should get 01 02 03 04 05 06 07.

我想把字符串nachricht转换成字节,但是我不明白。任何人能帮请吗?我只是收到一些数字,没有文字和字母。另一种方法也是受欢迎的。我在System.out.println(nachricht)上得到的是7次[B@41c04778]但是我应该得到01 02 03 04 05 06 07。

2 个解决方案

#1


2  

Your problem is lineSystem.out.println(in)

你的问题是lineSystem.out.println(中)

It should be System.out.println(in[counter]);

它应该是System.out.println(在[计数器]);

#2


3  

This

[B@41c04778

indicates you're printing an array ([) of bytes (B).

指示您正在打印字节数组([)(B)。

Java arrays don't have a useful toString() implementation. The above is useful to understand since you'll do the same in the future. Obvious mnemonics exist for other primitive types.

Java数组没有一个有用的toString()实现。上面的内容对理解很有用,因为将来您也会这么做。其他原始类型存在明显的助记符。

#1


2  

Your problem is lineSystem.out.println(in)

你的问题是lineSystem.out.println(中)

It should be System.out.println(in[counter]);

它应该是System.out.println(在[计数器]);

#2


3  

This

[B@41c04778

indicates you're printing an array ([) of bytes (B).

指示您正在打印字节数组([)(B)。

Java arrays don't have a useful toString() implementation. The above is useful to understand since you'll do the same in the future. Obvious mnemonics exist for other primitive types.

Java数组没有一个有用的toString()实现。上面的内容对理解很有用,因为将来您也会这么做。其他原始类型存在明显的助记符。