gpt4 book ai didi

Java IO : Why does the numerical representation of line feed appear on the console when reading from stdin?

转载 作者:搜寻专家 更新时间:2023-11-01 01:49:41 25 4
gpt4 key购买 nike

为了更好地理解我在讲座中听到的内容(关于 Java 输入和输出流),我自己编写了这个小程序:

public static void main (String[] args) throws Exception {
int input;
FileOutputStream fos = new FileOutputStream("test.txt");

// 95 is the underscore-char ( _ ). I use it
// for to finish it reception of input.
while ((input = System.in.read()) != 95) {
fos.write(input);
out.println(input);
}

out.println("- Finished -");

fos.close();
}

它将我刚刚输入的字符的数字表示打印到标准输出。它基本上可以工作,但这是我在 Eclipse 中看到的:

Screeshot Eclipse

“10”是换行符的十进制 ASCII 表示。

好的。我已经按下回车键以完成迭代。

但是为什么第二个值也会出现呢?

我希望只出现第一个键(实际字符)。

如果能以某种方式解释这个问题,那么我将不胜感激他/她的回答。

@Sanket Makani这是文本文件“text.txt”的相应内容:

2
3
A
a

在 Eclipse 中:

Screenshot

最佳答案

InputStreams 可用于二进制格式,二进制格式不关心过滤换行符。

您需要自己过滤它们,或者使用缓冲阅读器/扫描仪和读取行,然后遍历字符串中的字符。

https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()

表明它确实一次只读取一个字符,但是在您按下 enter 之前,eclipse 终端可能不会转发输入的数据。

当发生这种情况时,您的循环将运行两次。

扫描仪文档:https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextLine--

关于Java IO : Why does the numerical representation of line feed appear on the console when reading from stdin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44236431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com