据我所知,从Java文件中读取基于字符的数据的两种最常用的方法是使用Scanner或BufferedReader.我也知道BufferedReader通过使用缓冲区来有效地读取文件以避免物理磁盘操作.我的问题是:
Scanner执行以及BufferedReader?Scanner,BufferedReader反之亦然?嗨,我是新手Java,我想知道在控制台中读取用户输入的最佳选择是什么,据我所知,有3种方法可以做到:
Console console = System.console();BufferedReader input = new BufferedReader(new InputStreamReader(System.in));Scanner reader = new Scanner(System.in);我应该选择哪一个?为什么那个而不是其他的?
我正在尝试通过ScannerObject 读取命令.检查我使用的输入语法sc.hasNext()(对于缺少命令的情况).它已经很好地适用于许多情况,但现在我已经在JavaAPI中描述为"可以阻塞并等待输入"的情况.
该hasNext()方法何时阻止,我该如何控制它?有趣的事情是它在块之前的3个案例中完美地工作.此外,JavaAPI描述hasNext()了检查是否存在另一个Input的正确方法,以便Method next()不生成Exception.
这是我到目前为止所做的代码:
if (sc.hasNext() && sc.next().equals("create")) {
if (sc.hasNextInt()) {
width = sc.nextInt();
if (width > 0) {
if (sc.hasNextInt()) {
heigth = sc.nextInt();
if (heigth > 0) {
if (sc.hasNext()) { //At this point the hasNext Statement blocks for //no reason till an Input is made.
charset = sc.next();
Image = new AsciiImage(width, heigth,charset);
} else {
ret = false;
System.out.println("INPUT MISMATCH");
}
} ...//and …Run Code Online (Sandbox Code Playgroud)