简体   繁体   English

Java:输入流中的垃圾

[英]Java: trash in input Stream

I worte a small java function that calls another Java program and displays its input. 我编写了一个小的Java函数,该函数调用另一个Java程序并显示其输入。

private static void call() throws Exception 
{
    int  line;                             
    ///Other stuff here
    Process p2= Runtime.getRuntime().exec("java SelfModifying");
    InputStream is = p2.getInputStream();
    //p.waitFor();
    while ((line = is.read()) != -1) {
        System.out.println("result: " + line);
    }       
    Runtime.getRuntime().exit(0);
}

The prorgam that gests called is supposed to return a single int value: '10'. gest调用的程序应该返回一个int值:“ 10”。
Instead, I get 4 lines: result: 49 result: 48 result: 13 result: 10 相反,我得到4行:结果:49结果:48结果:13结果:10

Where do the three other values come from? 其他三个值从何而来? They are deterministic but seem to come from the input. 它们是确定性的,但似乎来自输入。 When I run the program on its own it does not return these 3 lines. 当我自己运行程序时,它不会返回这3行。

You're reading individual bytes from the stream: 您正在从流中读取单个字节:

  • 49 is ASCII '1' ; 49是ASCII'1 '1' ;
  • 48 is ASCII '0' ; 48是ASCII'0 '0' ;
  • 13 is ASCII '\\r' ; 13是ASCII '\\r' ;
  • 10 is ASCII '\\n' . 10是ASCII '\\n'

So the contents of the file is 10\\r\\n (10, followed by a windows newline). 因此,文件的内容为10\\r\\n (10,后跟Windows换行符)。

You should wrap is in a scanner: 你应该换行is在扫描仪:

Scanner scanner = new Scanner(is, "UTF-8");
System.out.println(scanner.nextInt());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM