How to set stdin mode to binary in Java?

心已入冬 提交于 2019-12-11 09:45:21

问题


What is the equivalent of this C++ line of code in Java, which sets stdin mode to binary:

_setmode(_fileno(stdin),_O_BINARY);

Thanks.


回答1:


None. _setmode(_fileno(stdin),_O_BINARY); on Windows is used to switch from text mode to binary mode, which prevents \n from being replaced with \r\n when reading input.

System.in is a generic InputStream, whose read method returns the next byte, without assuming anything about the type of input:

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.

Therefore there is no need for "disabling" text mode, as it was never "enabled" in the first place.


If you're not convinced by the contract, just read the source code and you will see that binary mode is activated (for stdin, stdout and stderr) when the JVM initialized: 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);
}


来源:https://stackoverflow.com/questions/31320329/how-to-set-stdin-mode-to-binary-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!