gpt4 book ai didi

Java InputStreamReader 不变的停顿

转载 作者:行者123 更新时间:2023-12-02 05:35:16 28 4
gpt4 key购买 nike

这是我的代码:

public static void main(String[] args) {
String in = "";

InputStreamReader reader = new InputStreamReader(System.in);

int ch;
StringBuilder sb = new StringBuilder();

System.out.println("paste text below:");

try {
while ((ch = reader.read()) != -1 && ch != 0) {
sb.append((char)ch);
}
}catch (IOException e) {
System.err.println(e.toString());
}
}
in = sb.toString();
System.out.println(in);
}

我已经调试过,它会遍历所有内容并在换行符上打印每个字符,但在读取最后一个字符后它总是会停止。我简单地输入了 asdfasdf以及复制并粘贴《独立声明》。它一直运行到结束,然后停止。

这甚至不像是一个无限循环,因为我在代码的每个部分都放置了一个 System.out.print("!@#$%") ,它就停止了......我的代码中没有无限循环代码。我非常确定InputStreamReader -- reader -- 陷入了它自己的无限循环中,因为它永远不会返回 -1。事实上,当它到达末尾时,它永远不会返回任何内容(尽管它在循环中返回正确的整数/字符)。

有谁知道发生了什么事或者有人遇到过类似的问题吗?有没有办法解决这个问题(不要说 BufferedReader 因为我需要读取带有多个换行符的文本,并且 BufferedReader 搜索第一个 \n ,所以我无法使用它)?

编辑:

我尝试读取字符缓冲区,然后使用字符串生成器......什么也没有。

答案:

您必须提供一个将打破循环的字符(否则请参阅 @default locales 的 answer )。

这是我的代码演变为:

public static void main(String[] args) {
InputStreamReader reader = new InputStreamReader(System.in);
StringBuilder sb = new StringBuilder();

int ch;

System.out.println("Paste text below (enter or append to text \"ALT + 1\" to exit):");

try {
while ((ch = reader.read()) != (char)63 /*(char)63 could just be ☺*/) {
sb.append(ch);
}
reader.close();
}catch (IOException e) {
System.err.println(e.toString());
}
String in = sb.toString();
System.out.println(in);
}

Alt + 1 returns (至少在 Windows 上)返回笑脸图标,但是您可以执行任何您想要的组合键,您所要做的就是找出 java 中的 char 并执行 while ((ch = reader.read()) != (char)charNumber .

最佳答案

基本上,reader.read()内部调用InputStream.read 。以下是文档中的引用:

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

换句话说,此方法将阻止程序执行并永远等待您的输入。

现在您可以看到当前状态下的程序永远不会停止执行:

//wait for user input forever
while ((ch = reader.read()) != -1 && ch != 0) {
//no matter what the input is just print it
System.out.println((char)ch);
} //continue waiting...

可能的解决方案:

  • 自定义退出策略,例如当用户输入 Ω 时中断循环,或者当用户连续输入“KILL ME”三次,或者在第 200 个字符之后。
  • 在命令窗口中输入特殊的文件结束组合来关闭System.in 。这种方法通常涉及一些特定于操作系统/终端的黑客攻击。看看这个问题:How to send EOF via Windows terminal .
  • 实现非阻塞读取机制。看看这个问题:Is it possible to read from a InputStream with a timeout?

之前已经在 Stackoverflow 上提出过类似的问题:

关于Java InputStreamReader 不变的停顿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25040921/

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