Java无法读取写入标准输出的带符号的负字节

时间:2017-04-02 02:57:57

标签: java powershell pipe byte

我有2个类,第一个是将1和0的二进制字符串输入到标准输入中,并将字符串拆分为长度为8的子字符串以转换为字节,以便像这样写入标准输出:

byte b = (byte)Integer.parseInt(byteString, 2);
System.out.write(b);
System.out.flush();

第二个是管道传输第一个输出,最终将字节转回长二进制字符串,但目前我只是这样做:

int next;
    while((next = System.in.read())!=-1){
    System.out.print(next); System.out.print(" ");
    System.out.flush();
}

如果我在第一个类中使用System.out.write(b);替换System.out.print(b); System.out.print(" ");并使用一些小样本输入,则输出为-80 -84 83 11 98 -116 53 -119 49 27 10 -80 -72 104 -123 0

如果我将此输出传输到第二个类,则输出63 63 83 11 98 63 53 63 49 27 13 10 63 63 104 63 0 13 10

有两件事似乎正在发生,我无法弄清楚为什么,System.in.read()正在返回63,这是?的ASCII,当读取将被签名为负数的字节时,最后添加了回车+新行。我很难得到解决方案,非常感谢洞察力。

注意:我在Windows 10 PowerShell中运行它,但是在正常的命令行和Linux终端中,行为是预期的,所以问题只出现在PowerShell中!

2 个答案:

答案 0 :(得分:2)

我不使用powershell,但是一个小测试显示管道确实改变了输出,比如在末尾添加换行符和回车符,或者将字节0xA2转换为0x3f('?')。

在网上搜索我找到了Understanding the Windows PowerShell Pipeline。我没有阅读超过第一段,但包含一个提示:

  

管道在Windows PowerShell中几乎无处不在。虽然您在屏幕上看到文本,但Windows PowerShell 不会在命令之间传输文本。相反,它管道对象。

也许这会有所帮助:What exactly does the pipe | mean in PowerShell?

答案 1 :(得分:0)

int next;
while((next = System.in.read())!=-1){
    System.out.print(next); System.out.print(" ");
    System.out.flush();
}

字节用Java签名,InputStream.read()的结果也是如此。试试这个:

int next;
DataInputStream in = new DataInputStream(System.in);
for (;;)
{
    try
    {
        next = in.readUnsignedByte();
        System.out.print(next); System.out.print(" ");
        System.out.flush();
    }
    catch (EOFException exc)
    {
        break;
    }
}