Java中获取控制台输入的最佳方法是什么?

11

在Java中使用System.out.print等方法可以很容易地输出内容。

然而,输入似乎有些不同。有人建议使用java.util.Scanner,而另一些人则推荐使用java.io.BufferedReader,当然还有很多其他的建议。以上两种方法是最常用的。

在我看来,上述两种方法都不太理想。那么,在Java中从控制台窗口获取输入是否有更好的方法?如果没有,我应该选择哪一种方法呢?


4
请看这里:https://dev59.com/c3VC5IYBdhLWcg3wixw0#930073 - Adil Soomro
1
看一下JLine。它是一个类似于命令行的界面,具有命令历史记录、TAB自动完成等功能。 - Piotr Gwiazda
7个回答

6

我认为Scanner在两个方面非常有用,

1) you can get input from command prompt and infuture if you want to change to file system, it will be quick

2) While reading integer inputs you don't need to parse

我更喜欢使用扫描仪。


5

我认为,Scanner类非常有用。例如,在使用BufferedReader时,你需要一次读取一行并解析其值。但是在Scanner中,你可以使用nextInt()等方法轻松获取整数等数据。


2

扫描仪很方便,但比BufferedReader慢。


2
  1. For console input you can use System.console(), which is available in/after JAVA 1.6

    it has options for readPassword() (will not show entered character on console as well do not cache it) and readLine().

    String name = System.console().readLine(); //using java.io.*
    
  2. Scanner is easiest and good option for less inputs but it's a bit slower than other options like console() and bufferedReader() when you have so many inputs to handle.

    Scanner in = new Scanner(System.in); // using java.util.Scanner;
    String s = in.nextLine();            // for reading string
    int a = in.nextInt();                // for reading int
    float b = in.nextFloat();            // for reading float
    
  3. I personally like bufferedReader() as it will work with earlier versions and non-interactive environments as well plus is faster.

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));       // using java.io.*
    String name = reader.readLine(); // it reads everything into string
    

p.s: System.console() 方法在非交互环境(如 IDE)中无法工作。


1

1

我认为扫描器有点慢,但扫描器更好。扫描器的问题在于,在输入int后很难输入字符串,因为nextint不读取换行符或其他内容。但是你可以将其解析为int或long类型,在使用nextline()输入字符串后进行。这样,你就不必担心光标的位置了。例如:int a=Integer.parseInt(s.nextLine());


1

如果你使用的是Java 1.6或更高版本,我更喜欢使用控制台。

这是一个简单的一行代码。

String str = System.console().readLine();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接