为什么 CTRL + M 给出的 ASCII 值为 10(十进制值)。它实际上应该给出 13。我正在通过 putty 连接到 Amazon EC2 linux 实例。我执行下面的程序
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
public class NumbersConsole {
private static String ttyConfig;
public static void main(String[] args) {
try {
setTerminalToCBreak();
int i=0;
while (true) {
//System.out.println( ""+ i++ );
if ( System.in.available() != 0 ) {
int c = System.in.read();
System.out.println(c);
if ( c == 13 ) {
break;
}
}
} // end while
}
catch (IOException e) {
System.err.println("IOException");
}
catch (InterruptedException e) {
System.err.println("InterruptedException");
}
finally {
try {
stty( ttyConfig.trim() );
}
catch (Exception e) {
System.err.println("Exception restoring tty config");
}
}
}
private static void setTerminalToCBreak() throws IOException, InterruptedException {
ttyConfig = stty("-g");
// set the console to be character-buffered instead of line-buffered
stty("-icanon min 1");
// disable character echoing
stty("-echo");
}
/**
* Execute the stty command with the specified arguments
* against the current active terminal.
*/
private static String stty(final String args)
throws IOException, InterruptedException {
String cmd = "stty " + args + " < /dev/tty";
return exec(new String[] {
"sh",
"-c",
cmd
});
}
/**
* Execute the specified command and return the output
* (both stdout and stderr).
*/
private static String exec(final String[] cmd)
throws IOException, InterruptedException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
Process p = Runtime.getRuntime().exec(cmd);
int c;
InputStream in = p.getInputStream();
while ((c = in.read()) != -1) {
bout.write(c);
}
in = p.getErrorStream();
while ((c = in.read()) != -1) {
bout.write(c);
}
p.waitFor();
String result = new String(bout.toByteArray());
return result;
}
}
当我将输入作为 (CTRL + M) 时,我得到的显示值为 10。但我期望值为 13。请让我知道我是否遗漏了什么??
最佳答案
CR 到 LF 的转换由 tty 驱动程序处理。您正在调用 setTerminalToCBreak()
,它会操作 tty 设置(我认为它会禁用 erase、kill、werase 和 rprnt 特殊字符)。
默认情况下启用的 icrnl
设置会导致回车 (CR) 转换为换行符 (LF)。禁用它应该可以让您直接看到 CR 字符。设置 raw
模式会更改许多标志,包括关闭 icrnl
。 (弄清楚如何在 Java 中做到这一点留作练习。)
但要小心这样做。 Enter 或 Return 键通常会发送一个 CR 字符。将它翻译成 LF 是允许它标记行尾的原因。如果您关闭该翻译,您可能会破坏该行为,除非您自己处理 CR。
有关 tty 设置的更多信息,man tty
或关注 this link .
关于java - Linux 中的 ascii 码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8662075/