【问题标题】:What is the use of System.in.read()?System.in.read() 有什么用?
【发布时间】:2013-03-16 07:23:03
【问题描述】:

System.in.read()在java中有什么用?
请解释一下。

【问题讨论】:

  • docs.oracle.com/javase/7/docs/api/java/io/… 它从输入流中读取一个字节的数据。
  • 回答此类问题的人不应该支持这种行为,必须告诉谷歌并在此处提问之前尝试他的方法
  • @HussainAkhtarWahid “标准输入”的概念(和现实世界的用法)对于 Java 程序员来说可能非常陌生。虽然read 方法显然在Javadoc 中进行了解释,但System.in 的预期用途却没有。谷歌搜索 System.in 也没有透露太多信息。
  • 其实我是从谷歌上来的。

标签: java


【解决方案1】:

迟到两年半总比没有好,对吧?

int System.in.read() 从输入流中读取数据的下一个字节。但我相信你已经知道了,因为查找起来很简单。所以,你可能要问的是:

  • 当文档说它读取 byte 时,为什么要声明返回 int

  • 为什么它似乎返回垃圾? (我输入'9',但它返回57。)

它返回一个int,因为除了一个字节的所有可能值之外,它还需要能够返回一个额外的值来指示流结束。因此,它必须返回一个比byte 可以表达更多值的类型。

注意:他们本可以将其设为short,但他们选择了int,这可能是对C具有历史意义的帽子的一角,其getc()函数也返回@987654332 @,但更重要的是因为 short 使用起来有点麻烦,(该语言无法指定 short 文字,因此您必须指定 int 文字并将其转换为 short,)加上在某些架构上int 的性能比short 更好。

它似乎返回垃圾,因为当您将字符视为整数时,您看到的是该字符的 ASCII(*) 值。因此,“9”显示为 57。但如果将其转换为角色,则会得到“9”,所以一切正常。

这样想:如果您输入字符“9”,那么期望 System.in.read() 返回数字 9 是荒谬的,因为如果您输入了 @,您希望它返回什么数字987654340@?显然,字符必须映射到数字。 ASCII(*) 是一种将字符映射到数字的系统。在这个系统中,字符“9”映射到数字 57,而不是数字 9。

(*) 不一定是 ASCII;可能是其他编码,例如 UTF-16;但在绝大多数编码中,当然在所有流行的编码中,前 127 个值与 ASCII 相同。这包括所有英文字母数字字符和流行符号。

【讨论】:

  • 不是 ASCII 值; UTF-16 代码单元。 “9”->57。 "?" -> [55349, 56320]
  • @TomBlodget 我认为它不会返回 UTF-16 代码。它将输入流视为字节流,因此它将返回一个字节。如果流恰好是(比如小端)UTF-16 字符流,那么它仍然会返回字节,首先是 UTF-16 字符的低字节,然后是高字节,然后是低字节下一个字符,以此类推。当然,我可能是错的。我还没有验证这一点。但是,你确定吗?
  • 你是对的。这些值来自控制台的编码。我只是指出控制台的编码不太可能是 ASCII。
  • @TomBlodget 哦,我明白了。当然。我做了一个更正。如果您仍然发现它有问题,请告诉我。
【解决方案2】:

也许这个例子会对你有所帮助。

import java.io.IOException;

public class MainClass {

    public static void main(String[] args) {
        int inChar;
        System.out.println("Enter a Character:");
        try {
            inChar = System.in.read();
            System.out.print("You entered ");
            System.out.println(inChar);
        }
        catch (IOException e){
            System.out.println("Error reading from user");
        }
    }
}

【讨论】:

  • 我没有返回正确的值:例如当我输入 10 时它返回 49。
  • 这是因为 '1' 的 ASCII 值是 49。如果将 int inChar 更改为 char inChar,这将按预期工作。
【解决方案3】:

Systemjava.lang 包中的最后一个类

来自api源代码的示例代码

public final class System {

   /**
     * The "standard" input stream. This stream is already
     * open and ready to supply input data. Typically this stream
     * corresponds to keyboard input or another input source specified by
     * the host environment or user.
     */
    public final static InputStream in = nullInputStream();

}

read()是抽象类InputStream的抽象方法

 /**
     * Reads the next byte of data from the input stream. The value byte is
     * returned as an <code>int</code> in the range <code>0</code> to
     * <code>255</code>. If no byte is available because the end of the stream
     * has been reached, the value <code>-1</code> is returned. This method
     * blocks until input data is available, the end of the stream is detected,
     * or an exception is thrown.
     *
     * <p> A subclass must provide an implementation of this method.
     *
     * @return     the next byte of data, or <code>-1</code> if the end of the
     *             stream is reached.
     * @exception  IOException  if an I/O error occurs.
     */
    public abstract int read() throws IOException;

简而言之,来自 api:

从输入流中读取一些字节并将它们存储到 缓冲区数组 b.实际读取的字节数返回为 一个整数。此方法阻塞,直到输入数据可用,结束 检测到文件,或者抛出异常。

来自InputStream.html#read()

【讨论】:

    【解决方案4】:

    为了补充已接受的答案,您还可以像这样使用System.out.read()

    class Example {
        public static void main(String args[])
            throws java.io.IOException { // This works! No need to use try{// ...}catch(IOException ex){// ...}         
    
            System.out.println("Type a letter: ");
            char letter = (char) System.in.read();
            System.out.println("You typed the letter " + letter);
        }
    }
    

    【讨论】:

    • 这并没有提供问题的答案。一旦你有足够的reputation,你就可以comment on any post;相反,provide answers that don't require clarification from the asker。 - From Review
    • @GillesGouaillardet 真的,这个答案并不比公认的答案少,问题在于这个问题并不是真正的问题。
    • @GillesGouaillardet 哦,对不起!我认为这个网站的目的是为开发人员的问题提供文档。我只是举了一个不使用 try/catch 块的例子。
    • 为什么需要“抛出 java.io.IOException”?
    【解决方案5】:
    import java.io.IOException;
    
    class ExamTest{
    
        public static void main(String args[]) throws IOException{
            int sn=System.in.read();
            System.out.println(sn);
        }
    }
    
    

    如果你想获得字符输入,你必须像这样投射:char sn=(char) System.in.read()

    值字节以 int 形式返回,范围为 0 到 255。但是,与其他语言的方法不同,System.in.read() 一次只读取一个字节。

    【讨论】:

      【解决方案6】:

      System.in.read()standard input 读取。

      标准输入可用于在控制台环境中从用户那里获取输入,但由于此类用户界面没有编辑功能,因此标准输入的交互式使用仅限于教授编程的课程。

      标准输入的大多数生产用途是在设计用于在 Unix 命令行 pipelines 中工作的程序中。在这样的程序中,程序正在处理的有效负载来自标准输入,程序的结果被写入标准输出。在这种情况下,标准输入永远不会由用户直接编写,它是另一个程序的重定向输出或文件的内容。

      典型的管道如下所示:

      # list files and directories ordered by increasing size
      du -s * | sort -n
      

      sort 从标准输入读取它的数据,这实际上是du 命令的输出。排序后的数据被写入sort的标准输出,默认在控制台上结束,并且可以很容易地重定向到一个文件或另一个命令。

      因此,标准输入在 Java 中相对较少使用。

      【讨论】:

        【解决方案7】:

        这个例子应该有帮助吗?当然还有 cmets >:)

        警告:在本段/帖子中,人是一个被过度使用的常用词

        总的来说我推荐使用Scanner类,因为你可以输入大句子,我不完全确定System.in.read有这些方面。如果可能,请纠正我。

        public class InputApp {
        
        // Don't worry, passing in args in the main method as one of the arguments isn't required MAN
        
            public static void main(String[] argumentalManWithAManDisorder){
                char inputManAger;
        
                System.out.println("Input Some Crap Man: ");
                try{
                    // If you forget to cast char you will FAIL YOUR TASK MAN
                    inputManAger = (char) System.in.read();
                    System.out.print("You entererd " + inputManAger + " MAN");
                }
                catch(Exception e){
                    System.out.println("ELEMENTARY SCHOOL MAN");
                }
            }
        }
        

        【讨论】:

        • 这...这真的很糟糕。
        【解决方案8】:

        它允许您从标准输入(主要是控制台)读取。 This SO question 可以帮到你。

        【讨论】:

          【解决方案9】:

          System.in.read() 是 System.in 类的读取输入法,它是“标准输入文件”或传统操作系统中的 0。

          【讨论】:

            【解决方案10】:

            system.in.read() 方法读取一个字节并以整数形式返回,但如果您输入 1 到 9 之间的 no ,它将返回 48+ 个值,因为在 ascii 代码表中,ascii 值 1-9 为 48 -57 。 希望,它会有所帮助。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-08-20
              • 2010-12-09
              • 2015-04-25
              • 1970-01-01
              • 1970-01-01
              • 2014-05-03
              • 1970-01-01
              相关资源
              最近更新 更多