为什么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中如何做到这一点还需要练习。)
但小心别这样做。回车键通常发送一个CR字符。把它翻译成LF,就可以标记一行的结尾。如果关闭该翻译,则可能会破坏该行为,除非您自己处理CR。
有关tty设置的更多信息,请man tty或按this link操作。

关于java - Linux中的ASCII代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8662075/

10-12 12:49
查看更多