scanner读文件两例

来源:互联网 发布:单片机应用系统设计 编辑:程序博客网 时间:2024/05/18 00:16

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

处理程序:

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("hrinfo1.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
}
}
结果:
C:/aaa>java SurnameReader
老赵 28 feb-01 true
小竹 22 dec-03 false
阿波 21 dec-03 false
凯子 25 dec-03 true
例子2:(用,分隔)hrinfo.txt
老赵,28,feb-01,true
小竹,22,dec-03,false
阿波,21,dec-03,false
凯子,25,dec-03,true

处理程序:
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]);
}
}
结果:
C:/aaa>java readhuman hrinfo.txt
姓名:老赵 ,年龄:28 ,入司时间:feb-01 ,验证标记:true
姓名:小竹 ,年龄:22 ,入司时间:dec-03 ,验证标记:false
姓名:阿波 ,年龄:21 ,入司时间:dec-03 ,验证标记:false
姓名:凯子 ,年龄:25 ,入司时间:dec-03 ,验证标记:true

原创粉丝点击