我有一个大小和内容未知的 .txt 文件。我想从文件中读入客户数据:
“NAME”-fName 包含字母 secName 可以是字母和/或数字
“AGE”——只是数字
“STUDENT.NO”-可以是字母和数字(设定长度)
每条信息都位于 .txt 中的新行中,因此前 3 行=学生 1,接下来 3 行=学生 2 等。
最终目标是以 3 个为一组迭代每个学生,验证数据并导出到不同的文件。如何提取前三行并验证每个姓名、年龄、号码的数据。
String fileName = "\\Users\\under\\Documents\\NetBeansProjects\\CA-Jan24\\students.txt";
String line = null;
BufferedReader br = new BufferedReader(new FileReader(fileName));
int i = 0;
try {
//print first 3 lines or all if file has less than 3 lines
while(((line = br.readLine()) != null) && i < 3) {
System.out.println(line);
i++;
//I get multi line String but dont know how to isolate eah line of info to put through if, else statement
}
}
finally {
br.close();
}
}
}
正如 ControlAltDel 所说,我认为这是一个非常好的方法。 满足要求的另一种更快的方法(不是最好的)是下面所附的方法。 如果数据不是以 3 行为一组,则此解决方案不起作用。 (变量 i 对于了解我是否正在读取名字、姓氏或年龄数据很有用。)
String fileName = "C:\\Users\\Usuario\\Documents\\test.txt";
String line = null;
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
int i = 0;
//print first 3 lines or all if file has less than 3 lines
while (((line = br.readLine()) != null)) {
switch (i) {
case 0:
System.out.println("line name = " + line + " is valid? " + Pattern.matches("[a-zA-Z]+", line));
//store in temporary variable to proceed with dumping later
break;
case 1:
System.out.println("line sec name = " + line + " is valid ? " + Pattern.matches("[a-zA-Z0-9]+", line));
//store in temporary variable to proceed with dumping later
break;
default: {
System.out.println("line age = " + line + " is valid? " + Pattern.matches("\\d+", line));
//store in temporary variable to proceed with dumping later
i = 0; //Reset i
}
}
i++;
//I get multi line String but dont know how to isolate eah line of info to put through if, else statement
}
}
除了
while
循环的条件之外,你还可以在其他地方调用readLine()。
由于只要我们在文件中遇到名称行(而不仅仅是任何行),您就想继续阅读,因此您应该更改此设置:
String line = null;
对此:
String nameLine;
(无需初始化它,因为程序将在任何代码尝试使用它之前为其赋值。编译器将强制执行此操作。)
在循环中,任何时候遇到 Name 行,您都可以放心地假设它后面会跟着 Age 行和 Student 行。 (至少,这是我的理解;如果我错了,请随时纠正我。)
try (BufferedReader br = Files.newBufferedReader(Path.of(fileName))) {
while ((nameLine = br.readLine()) != null) {
String ageLine = br.readLine();
String studentNumberLine = br.readLine();
// Use nameLine, ageLine, and studentNumberLine to write to file
}
}
一些小注意事项:
try
之后的括号中称为 try with resources 语句。它会导致编译器自动生成一个finally块来关闭BufferedReader。