(1)讀取文件中內容
jdk 5.0新增加了Scanner類,Scanner是一個可以使用正則表達式來解析基本類型和字符串的簡單文本掃描器,Scanner 使用分隔符模式將其輸入分解為標記,默認情況下該分隔符模式與空白匹配(可以使用s.useDelimiter("Pattern || String")指定分隔符)。然后可以使用不同的 next 方法將得到的標記轉換為不同類型的值。
new.txt: java ejb jdk j2me spring jdk flex silverlight jdk j2me j2ee jdk c# asp.net
輸出結果: java ejb j2me spring flex silverlight j2me j2ee c# asp.net
new.txt: java ejb jdk j2me spring jdk flex silverlight jdk j2me j2ee jdk c# asp.net
輸出結果: java ejb j2me spring flex silverlight j2me j2ee c# asp.net
Java代碼
- import java.io.*;
- import java.util.Scanner;
- public class ScanXan {
- public static void main(String[] args) throws IOException {
- Scanner s = null;
- try {
- s = new Scanner(new BufferedReader(new FileReader("c:\\new.txt")));
- //使用字符串jdk作為分隔符
- s.useDelimiter("jdk");
- while (s.hasNext()) {
- System.out.println(s.next());
- }
- } finally {
- if (s != null) {
- s.close();
- }
- }
- }
- }
(2)讀取控制台輸入
import java.util.Scanner;
public class ScannerTest
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
//receive string
String str = s.next();
//receive integer
Integer i = s.nextInt();
//receive double
Double d = s.nextDouble();
System.out.println(str+i+d);
}
}
int x=scanner.nextInt();這表示只接收int類型的數據,如果輸入其他的數據要出問題的