首页 > 解决方案 > 在检查 available() 后调用 read() 时,stdin 没有在 Windows 上回显(可中断的 readline 实现)

问题描述

我正在尝试在 Java 中实现可中断的 readline 方法 [1],因为标准例程(使用 System.in 周围的缓冲读取器)不是。我想出了一个在 Linux 上运行良好的例程,但是当你在 Windows 中运行它时,在用户按下回车键之前,按键不会回显到控制台 - 啊!

System.in.read()经过一些试验,似乎只有在用户键入时有阻塞调用时才会回显按键。

有谁知道这是否可以修复?我试图反映我使用私有java.ui.Console#echo方法的方式,但它似乎没有做任何事情。我的下一个停靠点是查看 JNA API,看看我是否可以从那里直接访问控制台。

1 - 作为参考,这是我的可中断 readline 实现。我捕获 ctrl-c 并中断调用 readline 的线程 - 在其他地方处理,工作,并且可能与此示例无关

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

public class EchoTest {

  private static final long MILLIS_BETWEEN_STDIN_CHECKS = 10;

  public static void main(String[] args) throws IOException, InterruptedException {
    System.out.println("Type something");
    // on windows, there's no echo until enter, dammit!
    String input = readline(System.in);
    System.out.println("Hello, " + input);
  }


  /**
   * Read a line of input from an input stream, presumably stdin.
   *
   * @param stdin An InputStream to read a line from. 
   *
   * @return the string that was read, with the line terminator removed.
   *
   * @throws IOException if there was an io error reading from stdin
   * @throws InterruptedException if the thread was interrupted while waiting to receive keypresses
   */
  public static String readline(InputStream stdin) throws IOException, InterruptedException {

    // we use mark to peek ahead for \r\n
    if (!stdin.markSupported()) {
      throw new IllegalArgumentException("stdin must support mark");
    }

    // result is stored in here
    StringBuffer stringBuffer = new StringBuffer(512);
    // a byte buffer as we read a byte at a time from stdin
    byte[] bytes = new byte[64];
    // number of bytes we've read in to the buffer
    int bytesRead = 0;

    while (true) {

      // check whether read should block
      if (stdin.available() > 0) {

        int byteRead = stdin.read();

        if (byteRead == -1) {
          // end of stream - not expected for readline
          throw new EOFException();
        }

        // check for line ending character sequences, we need to detect \r, \n or \r\n
        if (byteRead == '\n') {
          // we're done!
          break;
        } else if (byteRead == '\r') {
          // we're done, but we might need to consume a trailing \n
          if (stdin.available() == 0) {
            // nothing is ready, we presume that if \r\n was sent, then they'd be sent as one and the buffer would
            // already have the \n
            // worst case, the next call to readline will exit with an empty string - if this appears to happen, we
            // could detect a \n being in stdin at the start and drop it on the floor
            break;
          } else {
            // there is a byte there - mark our position and check if it's \n
            stdin.mark(1);
            if (stdin.read() == '\n') {
              // it is we're done
              break;
            } else {
              // it isn't \n, reset position for the next call to readline or read
              stdin.reset();
              break;
            }
          }
        } else {
          bytes[bytesRead++] = (byte)byteRead;

          // flush buffer if it's full
          if (bytesRead == bytes.length) {
            stringBuffer.append(new String(bytes, 0, bytesRead));
            bytesRead = 0;
          }

        }

      } else {
        if (Thread.interrupted()) {
          throw new InterruptedException();
        } else {
          Thread.sleep(MILLIS_BETWEEN_STDIN_CHECKS);
        }
      }

    }

    stringBuffer.append(new String(bytes, 0, bytesRead));

    return stringBuffer.toString();
  }


}

标签: javawindowsconsole

解决方案


推荐阅读