這幾天想用Java擷取控制台輸入,用到了Scanner,後來還用到了Scanner讀取檔案的功能,現在總結一下。
API:http://tool.oschina.net/apidocs/apidoc?api=jdk_6u30
java.util.Scanner是Java5的新特征,主要功能是簡化文本掃描、擷取控制台輸入。
下面是一些使用示例:
一、擷取控制台輸入
import java.util.Scanner;
public class TestScanner {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("Waiting input");
while (true) {
String temp = scn.nextLine();
if (temp.trim().equals("exit")) {
return;
}
System.out.println("Your input is: " + temp);
}
}
}
通過new Scanner(Sysem.in)建立一個Scanner,控制台會一直等待輸入,直到敲回車結束,把所輸入的内容傳給Scanner,作為掃描對象。如果要擷取輸入的内容,則隻需要調用Scanner的nextLine()(或者next())方法即可。
補充:nextLine()和next()方法的差別:
nextLine()運作結果:
改成next()之後,運作結果為:
差別顯而易見:
scanner可以允許輸入多行,
next() 每次取到一個間隔符前面的資料 如: 輸入 Hello World 取值應該是Hello,因為Hello後面有空格
nextLine() 每次取一個換行符前面的資料 如:輸入 Hello World 回車,取值 就是Hello World
nextInt() 是取next() 然後把字元串解析成一個int數字。(此外,還有nextLong()、nextShort()方法,可參見API)
hasNextInt() 是判斷下次調用next()是否可以得到一個可以安全解析成int的字元串。如果已經到達輸入的結尾,或者下一個next()的傳回值不能解析為一個數字,即不符合數字的格式,那麼傳回false。
重要的一點:如果不使用Scanner,用其他方法擷取控制台輸入比較痛苦。
1、使用System.in
public class UseSystemIn {
public static void main(String[] args) {
System.out.println("Waiting input");
byte[] b = new byte[1024]; // 數組緩沖
int n = 0; // 有效資料個數
try {
while (true) {
// The number of bytes actually read is returned as an integer.
n = System.in.read(b); // Reads some number of bytes from the input stream and stores them into the buffer array b
String s = new String(b, 0, n-2); // 轉換為字元串
if (s.equalsIgnoreCase("exit")) {
break; // 結束循環
}
System.out.println("Your input is: " + s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
上述代碼中,加入了一個while循環,可以讓使用者輸入多次。在使用者輸入時,送入輸入流的内容除了使用者輸入的内容以外,還包含了“\r\n”這兩個字元,是以在将輸入的内容和eixt進行比較時,去掉讀出的最後兩個字元,将剩餘的内容轉換為字元串。
運作結果:
2、使用BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class UseBufferedReader {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Waiting input");
String line = null;
try {
while ((line = br.readLine()) != null) {
System.out.println("Your input is: " + line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
這裡注意,對BufferedReader對象的建立,上述代碼運作結果如下,用Ctrl+z來結束輸入。
二、讀取檔案内容
借助Scanner的構造函數。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileUseScanner {
public static void main(String[] args) {
Scanner scn = null;
try {
scn = new Scanner(new File("D:\\test\\input.txt"));
while (scn.hasNextLine()) {
System.out.println(scn.nextLine());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注意:Scanner有很多構造函數,這裡還可以使用scn = new Scanner(new FileInputStream(new File("D:\\test\\input.txt"))); —— 使用Scanner(InputStream source)
三、Scanner預設使用空格作為分隔符來分隔文本,但允許指定新的分隔符
使用預設的空格符:
import java.util.Scanner;
public class UseDelimiterScanner {
public static void main(String[] args) {
Scanner scn = new Scanner(
"123 asdf sd 45 789 sdf asdfl,sdf.sdfl,asdf ......asdfkl las");
// scn.useDelimiter(" |,|\\.");
while (scn.hasNext()) {
System.out.println(scn.next());
}
}
}
此時的運作結果為:
将注釋行去掉,使用空格或逗号或點号作為分隔符,輸出結果如下:
該運作結果中的空行,與空格數、逗号和點号的數目有關系,一個逗号的時候沒有空行,n個逗号或其他的時候,有n-1個空行。
其他檢視API。
參考:http://lavasoft.blog.51cto.com/62575/182467/
http://www.cnblogs.com/ydpvictor/archive/2012/06/17/2552981.html
http://www.cnblogs.com/springcsc/archive/2009/12/03/1616372.html