scanner两个例子(转)

本文介绍了一个Java程序示例,展示了如何从文本文件中读取数据,并按指定格式解析这些数据。通过使用Java的FileReader和Scanner类,程序能够逐行读取并解析包含姓名、年龄等信息的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.FileReader;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class SurnameReader {
public static void main(String args[]) throws FileNotFoundException {
FileReader fileReader =new FileReader("src/test.txt");
// create a scanner from the data file
Scanner scanner = new Scanner(fileReader);
// repeat while there is a next item to be scanned
while (scanner.hasNext()) { //一行一行的读入
// retrieve each data element
String name = scanner.next();
int age = scanner.nextInt();
String time = scanner.next();
boolean bool = scanner.nextBoolean();
System.out.println(name+" "+age+" "+time+" "+bool); //一行一行的输出
}

scanner.close(); // also closes the FileReader
}
}


test.txt
老赵 28 feb-01 true
小竹 22 dec-03 false
阿波 21 dec-03 false
凯子 25 dec-03 true

执行结果如test.txt

以“,”分隔输入,默认是以空格输入

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

public class readhuman {
private static void readfile(String filename) {
try {
Scanner scanner = new Scanner(new File(filename));
// Scanner使用空白符作为默认的分隔符,用户可以很容易地更改分隔符的默认设置。
scanner.useDelimiter(System.getProperty("line.separator"));
while (scanner.hasNext()) {
parseline(scanner.next());
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println(e);
}
}

private static void parseline(String line) {
Scanner linescanner = new Scanner(line);
// Scanner使用空白符作为默认的分隔符,用户可以很容易地更改分隔符的默认设置。
linescanner.useDelimiter(",");
// 可以修改usedelimiter参数以读取不同分隔符分隔的内容
String name = linescanner.next();
int age = linescanner.nextInt();
String idate = linescanner.next();
boolean iscertified = linescanner.nextBoolean();
System.out.println("姓名:" + name + " ,年龄:" + age + " ,入司时间:" + idate
+ " ,验证标记:" + iscertified);
}

public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java readhuman file_location");
System.exit(0);
}
readfile(args[0]); //参数为comma.txt
}
}


comma.txt
hell,28,feb-01,true

执行结果:
姓名:hell ,年龄:28 ,入司时间:feb-01 ,验证标记:true

源码见附件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值