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
源码见附件