java5新特性:java.util.Scanner主要功能是簡化文本掃描
1.掃描控制臺輸入:Scanner類
1.0 Scanner類優(yōu)化:close()方法
System.out.print("請輸入一個單詞:");
Scanner scan=new Scanner(System.in);
String str=scan.nextLine();
System.out.print("請輸入一個單詞:");
String str2=scan.nextLine();
··· ···
scan.close(); //釋放內(nèi)存
說明:使用close()方法關(guān)閉輸入流泉褐,釋放內(nèi)存
1.1 獲取單數(shù)據(jù)
當通過new Scanner(System.in)創(chuàng)建一個Scanner礼搁,控制臺會一直等待輸入,直到敲回車鍵結(jié)束篡帕,把所輸入的內(nèi)容傳給Scanner屑迂,作為掃描對象瑞驱。如果要獲取輸入的內(nèi)容竿音,則只需要調(diào)用Scanner的nextLine()方法即可和屎。
import java.util.Scanner;
System.out.print("請輸入一個單詞:");
String s1=scan.nextLine(); //獲取到一行輸入
String s2=scan.next(); //獲取到一個輸入,出現(xiàn)空格谍失、tab或回車就結(jié)束
int s3=scan.nextInt(); //獲取到一個數(shù)字眶俩,出現(xiàn)空格莹汤、tab或回車就結(jié)束
byte s4=scan.nextByte(); //獲取到一個字符快鱼,出現(xiàn)空格、tab或回車就結(jié)束
boolean s5=scan.nextBoolean(); //獲取到一個Boolean類纲岭,出現(xiàn)空格抹竹、tab或回車就結(jié)束
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
注意:nextLine() 獲取的是輸入的一行數(shù)據(jù);而next()等獲取的是一個數(shù)據(jù)止潮,若數(shù)據(jù)中存在空格窃判、tab、或回車喇闸,則都為該數(shù)據(jù)結(jié)束
輸入:
nihao hello world
hello 67 u true
輸出:
nihao hello world
hello
67
u
true
1.2 獲取數(shù)組
通常使用nextLine()來獲取到輸入行為String字符串袄琳,然后對字符串進行split處理
Scanner scan=new Scanner(System.in);
String str=scan.nextLine();
String[] strnum=str.split(" ");
System.out.println(strnum.length);
for(int i=0;i<strnum.length;i++){
System.out.println(strnum[i]);
}
scan.close();
1.3 逐行獲取輸入數(shù)據(jù)或文件,然后處理
使用hasNextLine()方法:
while(scan.hasNextLine()){
System.out.println(scan.nextLine());
//補充使用到的方法
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
InputStream in = null;
try {
in = new FileInputStream(new File("文件完整路徑")); //路徑("C:\\AutoSubmit.java"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Scanner a = new Scanner(in);
while(a.hasNextLine()){
System.out.println(a.nextLine());
}
2. 掃描控制臺輸入:BufferReader類
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
System.out.println(str);
2.1 逐行掃描文件燃乍,并逐行輸出:BufferReader類
這里暫時缺失唆樊,待補充
BufferReader 也可以讀取鍵盤的輸入,那么他們有什么區(qū)別啊 ?
由于用戶的每次鍵盤輸入都被BufferReader 當做了字符串String 來處理刻蟹。
BufferReader 不能夠讀取基本類型輸入項逗旁,它總是讀取String 對象。