0
点赞
收藏
分享

微信扫一扫

00023.03 文本扫描仪:Scanner(可以很方便读取任意文本)


Scanner目录

文章目录

  • ​​Scanner目录​​
  • ​​前言​​
  • ​​一、是什么?​​
  • ​​二、代码​​
  • ​​总结​​

前言

Scanner,说起它,我们的第一反应一定是键盘输入吧,但是事实上键盘输入我们只是用到了它的一小部分
它并不是只为键盘输入而设计的

一、是什么?

System.in:默认情况下是从键盘输入的数据中扫描,实际上,Scanner:可以从你指定的文件、流中读取文本数据

原来的使用方式:

00023.03 文本扫描仪:Scanner(可以很方便读取任意文本)_Scanner

system.in

00023.03 文本扫描仪:Scanner(可以很方便读取任意文本)_Scanner_02


现在的使用方式,实际上有很多:

next()不会吸取字符前/后的空格/Tab键,只吸取字符,开始吸取字符(字符前后不算)直到遇到空格/Tab键/回车截止吸取;

nextLine()吸取字符前后的空格/Tab键,回车键截止

00023.03 文本扫描仪:Scanner(可以很方便读取任意文本)_文本扫描_03


00023.03 文本扫描仪:Scanner(可以很方便读取任意文本)_Test_04


00023.03 文本扫描仪:Scanner(可以很方便读取任意文本)_文本扫描_05


也可自定义字符编码

00023.03 文本扫描仪:Scanner(可以很方便读取任意文本)_Test_06

二、代码

package com.atguigu.test03;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

import org.junit.Test;

/*
* System.in:默认情况下是从键盘输入的数据中扫描
* Scanner:可以从你指定的文件、流中读取文本数据
*/
public class TestScanner {
@Test
public void test05() throws FileNotFoundException{
Scanner input = new Scanner(new File("d:/1.txt"),"GBK");//InputStream

while(input.hasNextLine()){
String line = input.nextLine();
System.out.println(line);
}

input.close();
}

@Test
public void test04() throws FileNotFoundException{
Scanner input = new Scanner("1.txt");//InputStream

while(input.hasNextLine()){
String line = input.nextLine();
System.out.println(line);
}

input.close();
}

@Test
public void test03() throws FileNotFoundException{
Scanner input = new Scanner(new File("1.txt"));//InputStream

while(input.hasNextLine()){
String line = input.nextLine();
System.out.println(line);
}

input.close();
}

@Test
public void test02() throws FileNotFoundException{
Scanner input = new Scanner(new FileInputStream("1.txt"));//InputStream

while(input.hasNextLine()){
String line = input.nextLine();
System.out.println(line);
}

input.close();
}

@Test
public void test01(){
Scanner input = new Scanner(System.in);
System.out.print("请输入一个整数:");
int num = input.nextInt();
System.out.println("num = " + num);
input.close();
}
}

总结

1、System.in:默认情况下是从键盘输入的数据中扫描,实际上,Scanner:可以从你指定的文件、流中读取文本数据
2、Scanner虽然很强大,但是需要注意它只能读取文本


举报

相关推荐

0 条评论