一个可以使用正则表达式来解析基本类型和字符串的简单文本扫描器。
Scanner
使用分隔符模式将其输入分解为标记,默认情况下该分隔符模式与空白匹配。然后可以使用不同的 next 方法将得到的标记转换为不同类型的值。
例如,以下代码使用户能够从 System.in 中读取一个数:
Scanner sc = new Scanner(System.in); int i = sc.nextInt();
再看一个例子,以下代码使 long
类型可以通过 myNumbers
文件中的项分配:
Scanner sc = new Scanner(new File("myNumbers")); while (sc.hasNextLong()) { long aLong = sc.nextLong(); }
PrintWriter:
public class PrintWriter extends Writer
向文本输出流打印对象的格式化表示形式。此类实现在 PrintStream
中的所有 print 方法。它不包含用于写入原始字节的方法,对于这些字节,程序应该使用未编码的字节流进行写入。
与 PrintStream
类不同,如果启用了自动刷新,则只有在调用println、printf 或 format 的其中一个方法时才可能完成此操作,而不是每当正好输出换行符时才完成。这些方法使用平台自有的行分隔符概念,而不是换行符。
此类中的方法不会抛出 I/O 异常,尽管其某些构造方法可能抛出异常。客户端可能会查询调用 checkError()
是否出现错误。
实例: 对员工信息进行文件写入并读出:
import java.io.*;
import java.util.*;
class Employee {
String name;
float salary;
int year;
int month;
int day;
Employee() {
}
Employee(String a, float b, int c, int d, int e) {
name = a;
salary = b;
year = c;
month = d;
day = e;
}
public String toString() {
return "[" + name + "," + salary + "," + year + "," + month + "," + day
+ "]";
}
public void writeData(PrintWriter out) {
out.println(name + "|" + salary + "|" + year + "|" + month + "|" + day);
}
public void readData(Scanner in) {
String line = in.nextLine();
String[] tokens = line.split("\\|");
name = tokens[0];
salary = Float.parseFloat(tokens[1]);
year = Integer.parseInt(tokens[2]);
month = Integer.parseInt(tokens[3]);
day = Integer.parseInt(tokens[4]);
}
}
public class TextFileTest {
public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee("张三", 5000, 1990, 9, 1);
staff[1] = new Employee("李四", 6000, 1909, 9, 3);
staff[2] = new Employee("王五", 7000, 1981, 9, 10);
try {
PrintWriter out = new PrintWriter("employee.dat");
writeData(staff, out);
out.close();
Scanner in = new Scanner(new FileReader("employee.dat"));
Employee[] newStaff = readData(in);
in.close();
for (int i = 0; i < newStaff.length; i++) {
System.out.println(newStaff[i].toString());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// File file = new File("employee.dat");
// file.delete();
}
public static void writeData(Employee[] emp, PrintWriter out) {
out.println(emp.length);
for (int i = 0; i < emp.length; i++) {
emp[i].writeData(out);
}
}
public static Employee[] readData(Scanner in) {
int n = in.nextInt();
in.nextLine();
Employee employees[] = new Employee[n];
for (int i = 0; i < n; i++) {
employees[i] = new Employee();
employees[i].readData(in);
}
return employees;
}
}