如何在 Java 中将标准输入模式设置为二进制?

How to set stdin mode to binary in Java?

Java 中这行 C++ 代码的等价物是什么,它将 stdin 模式设置为二进制:

_setmode(_fileno(stdin),_O_BINARY);

谢谢。

None。 Windows上的_setmode(_fileno(stdin),_O_BINARY);用于从文本模式切换到二进制模式,防止在读取输入时\n被替换为\r\n

System.in is a generic InputStream, whose read method returns 下一个字节,不假设任何输入类型:

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.

因此不需要 "disabling" 文本模式,因为它从来就不是 "enabled"。


如果你不相信合同,只要阅读源代码,你会看到当 JVM 初始化时,二进制模式被激活(对于 stdin、stdout 和 stderr):http://hg.openjdk.java.net/jdk7u/jdk7u/hotspot/file/34aea5177b9c/src/os/windows/vm/os_windows.cpp#l3716:

void os::win32::setmode_streams() {
  _setmode(_fileno(stdin), _O_BINARY);
  _setmode(_fileno(stdout), _O_BINARY);
  _setmode(_fileno(stderr), _O_BINARY);
}