1、JDK 1.4 及以下版本讀取的方法
JDK 1.4 及以下的版本中要想從控制臺(tái)中輸入數(shù)據(jù)只有一種辦法,即使用System.in獲得系統(tǒng)的輸入流,再橋接至字符流從字符流中讀入數(shù)據(jù)。只能讀取字符串,若需要讀取其他類型的數(shù)據(jù)需要手工進(jìn)行轉(zhuǎn)換。代碼如下:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = null;
try
{
str = br.readLine();
System.out.println(str);
}
catch (IOException e)
{
e.printStackTrace();
}
2、JDK 5.0 讀取的方法
從 JDK 5.0 開始,基本類庫中增加了java.util.Scanner類,根據(jù)它的 API 文檔說明,這個(gè)類是采用正則表達(dá)式進(jìn)行基本類型和字符串分析的文本掃描器。使用它的Scanner(InputStream source)構(gòu)造方法,可以傳入系統(tǒng)的輸入流System.in而從控制臺(tái)中讀取數(shù)據(jù)。canner不僅可以從控制臺(tái)中讀取字符串,還可以讀取除char之外的其他七種基本類型和兩個(gè)大數(shù)字類型,并不需要顯式地進(jìn)行手工轉(zhuǎn)換。代碼如下:
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
System.out.println(str);
3、JDK 6.0 讀取的方法
從 JDK 6.0 開始,基本類庫中增加了java.io.Console類,用于獲得與當(dāng)前 Java 虛擬機(jī)關(guān)聯(lián)的基于字符的控制臺(tái)設(shè)備。在純字符的控制臺(tái)界面下,可以更加方便地讀取數(shù)據(jù)。代碼如下:
Console console = System.console();
if (console == null)
{
throw new IllegalStateException("不能使用控制臺(tái)");
}
String str = console.readLine("console");
System.out.println(str);