如何在 Java 中将 stdin 模式设置为二进制? [英] How to set stdin mode to binary in Java?

查看:28
本文介绍了如何在 Java 中将 stdin 模式设置为二进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

_setmode(_fileno(stdin),_O_BINARY);

谢谢.

推荐答案

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

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 是一个通用的 InputStream,它的 read 方法 返回下一个字节,不假设输入类型:

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

从输入流中读取下一个字节的数据.值字节以 0 到 255 范围内的 int 形式返回.如果由于已到达流末尾而没有可用字节,则返回值 -1.此方法会阻塞,直到输入数据可用、检测到流结束或抛出异常为止.

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.

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

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);
}

这篇关于如何在 Java 中将 stdin 模式设置为二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆