(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类型的数据,如果输入其他的数据要出问题的