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

本文介绍了Java中的Scanner类,不仅限于从键盘获取输入,还可以从文件和流中读取文本数据。通过示例代码展示了如何使用Scanner读取指定文件的内容,包括使用不同构造方法和指定字符编码。总结了Scanner的主要功能和注意事项,强调其在读取文本方面的灵活性。
摘要由CSDN通过智能技术生成

Scanner目录

前言

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

一、是什么?

System.in:默认情况下是从键盘输入的数据中扫描,实际上,Scanner:可以从你指定的文件、流中读取文本数据
原来的使用方式:
在这里插入图片描述

system.in
在这里插入图片描述
现在的使用方式,实际上有很多:
next()不会吸取字符前/后的空格/Tab键,只吸取字符,开始吸取字符(字符前后不算)直到遇到空格/Tab键/回车截止吸取;
nextLine()吸取字符前后的空格/Tab键,回车键截止
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
也可自定义字符编码
在这里插入图片描述

二、代码

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值