Scanner是一个专门进行输入流处理的程序类,这个类可以方便处理各种数据类型。Scanner类的主要的方法有
1. 判断是否有指定类型数据: public boolean hasNextXxx()
2. 取得指定类型的数据: public 数据类型 nextXxx()
3. 定义分隔符:public Scanner useDelimiter(Pattern pattern)
4. 构造方法:public Scanner(InputStream source)
基本语法:Scanner input=new Scanner(System.in);
范例:
- import java.io.FileNotFoundException;
- import java.util.Scanner;
-
- public class ScannerTest {
- public static void main(String[] args) throws FileNotFoundException {
- //从键盘中读入时
- Scanner input = new Scanner(System.in);
- System.out.println("使用nextLine接收内容:");
- if (input.hasNext() == true)//判断用户有没有输入字符串
- {
- String str = input.nextLine();
- System.out.println("输出内容:" + str);
- }
- input.close();
- }
- }
基本语法:Scanner input=new Scanner(new File(fileName));
范例:
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.util.Scanner;
-
- public class ScannerTest {
- public static void main(String[] args) throws FileNotFoundException {
- //从文件读取数据
- File file=new File("D:\\测试文夹\\aa.txt");
- Scanner scanner=new Scanner(file);
- while(scanner.hasNext())
- {
- System.out.println(scanner.next());
- }
- input.close();
- }
- }
可以从文件种读取也可以从web服务器中读取:
URL:统一资源定位器,web文件的唯一地址
URL url = new URL("www.google.com/index.html");
创建URL对象以后,使用URL类的openStream()方法获得输入流,使用这个输入流产生Scanner对象,如下
Scanner reader = new Scanner(url.openStream(),”utf-8”);
通过reader顺序读,获得资源中的文本数据。
范例:
- import java.io.IOException;
- import java.net.URL;
- import java.util.Scanner;
-
- public class ScannerTest {
- public static void main(String[] args) throws IOException {
- URL url=new URL("https://blog.csdn.net/xxxx/article/details/124229293");
- Scanner reader = new Scanner(url.openStream(),"utf-8");
- while(reader.hasNext()){
- System.out.println(reader.nextLine());
- }
- reader.close();
- }
- }
一般都是通过Scanner类的next()与nextLine()方法获取输入的字符串,在读取前一般通过hasNext()和hasNextLine()判断是否还有输入的数据,此时这俩种方法的区别是:
1.next:
2.nextLine:
代码展示:
1.nextLine的展示:
- Scanner input = new Scanner(System.in);
- System.out.println("使用nextLine接收内容:");
- if (input.hasNext() == true)//判断用户有没有输入字符串
- {
- String str = input.nextLine();
- System.out.println("输出内容:" + str);
- }
结果:

2.next的展示:
- Scanner input = new Scanner(System.in);
- System.out.println("使用next接收内容:");
- if (input.hasNext() == true)//判断用户有没有输入字符串
- {
- String str = input.next();
- System.out.println("输出内容:" + str);
- }
结果:

通过结果可以对比出区别。
范例:
- String s = "you are Beautiful!you are kind! you are smart!";
- Scanner scanner = new Scanner(s);
- scanner.useDelimiter("!");
-
- while (scanner.hasNext())
- System.out.println(scanner.next());
结果:
