IO流要“晚开早关”,Scanner对象也有close()方法,为什么总是无人问津呢?
[Java] 纯文本查看 复制代码 import java.util.Scanner;
public class ScannerQuestion1 {
public static void main(String[] args) throws Exception {
Scanner sc1 = new Scanner(System.in);
System.out.println("输入任意字符串:");
String s = sc1.nextLine();
System.out.println(s);
sc1.close();
Scanner sc2 = new Scanner(System.in);
System.out.println("输入任意字符串:");
s = sc2.nextLine();
System.out.println(s);
sc2.close();
}
}
运行结果:
输入任意字符串:
aaa
aaaException in thread "main"
输入任意字符串:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at lx.question.ScannerQuestion1.main(ScannerQuestion1.java:19)
这个异常有点难以明白,没找到line,没输入肯定找不到,为什么sc2不等输入就直接去找了呢?于是我们把sc1.close();注释掉。
运行结果:
输入任意字符串:
aaa
aaa
输入任意字符串:
bbb
bbb
这里sc2的nextLine()方法会等待你录入line后再读取,好像更迷糊了,我们换一种键盘录入流的创建方式试试。
[Java] 纯文本查看 复制代码 import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class ScannerQuestion1 {
public static void main(String[] args) throws Exception {
Scanner sc1 = new Scanner(System.in);
System.out.println("输入任意字符串:");
String s = sc1.nextLine();
System.out.println(s);
sc1.close();
/*Scanner sc2 = new Scanner(System.in);
System.out.println("输入任意字符串:");
s = sc2.nextLine();
sc2.close();*/
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
s = br.readLine();
System.out.println(s);
br.close();
}
}
运行结果:
输入任意字符串:
aaa
aaaException in thread "main"
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:170)
at java.io.BufferedInputStream.read(BufferedInputStream.java:336)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at lx.question.ScannerQuestion1.main(ScannerQuestion1.java:22)
这样就出现了很好辨识的异常信息,因为System.in被Scanner的close()关掉了。所以之后开启键盘输入流会出现异常。
这也是为什么可能会多次用到键盘输入时不调用Scanner的close()的方法的原因。 |