java - 使用字符串解析器并将输入文件传递给arraylist
问题描述
嗨,我正在尝试读取文件并将其存储在数组列表中,但我被困在这里。我还需要使用我不知道放在哪里的 String.split()。有什么我错过的吗?
我的代码是:
import java.util.ArrayList;
import java.io.*;
import java.util.Scanner;
public class Employee
{
private ArrayList<Employee> employees;
private String name;
public Employee()
{
employees = new ArrayList<Employee>();
name = "";
}
public void readFile()
{
String filename = ("employees.txt");
try
{ FileReader inputFile = new FileReader(filename);
try
{
while (parser.NextLine())
{
Scanner parser = new Scanner(inputFile);
String employeeType = parser.nextLine();
System.out.println(employeeType);
String employeeNumber = parser.nextLine();
System.out.println(employeeNumber);
String employeeName = parser.nextLine();
System.out.println(employeeName);
}
}
finally
{
System.out.println("Closing file");
inputFile.close();
}
}
catch (FileNotFoundException exception)
{
System.out.println(filename + "not found");
}
catch(IOException exception)
{
System.out.println("Unexpected I/O error occured");
}
}
}
解决方案
假设您有并输入文件如下:
jinny 程序员 50000
john manager 75000
您已经正确设置了一些东西,但是您必须考虑的是如何实例化 Employee(它似乎只有一个无参数构造函数)。假设Employee
有一个名字、一个头衔和一个薪水。这些是您的Employee
. 当您在文件中阅读时,您希望在Employee
阅读每一行时将这些属性设置为单一类型,其属性由示例文件中的空白字符分隔。
public class Employee {
private String name;
private String title;
private Integer salary;
//constructor + getters + setters
}
此外,对于遇到的每个员工,您都需要在员工之外构建一个包含您的员工信息的集合。
考虑以下可能存在于Employee
类之外的示例。这就是您从数据文件中收集员工并填充员工属性的方式。
public static void main(String... args) {
List<Employees> employees = readFile();
//continue work on employees here
}
public static List<Employee> readFile()
{
String filename = ("employees.txt");
try
{ FileReader inputFile = new FileReader(filename);
Scanner scanner = new Scanner(inputFile);
try
{
while (scanner.hasNextLine())
{
Employee e = new Employee();
String line = scanner.nextLine();
String [] lineSplit = line.split(" ");
//populate employees here OR use a constructor on employee that accepts all 3 parameters
}
}
//continue implementation here
推荐阅读
- visual-studio-code - 如何将 npm 下载位置从 github 重置为默认值
- java - 为什么我不能在 SimpleEntry 子类中调用 Long 对象的方法?
- elasticsearch - 用弹性搜索中的匹配值标记每个命中
- javascript - 如何添加反应原生博览会 Av 搜索栏
- php - 将一些 WooCommerce 产品数据传递给联系表 7 查询表“所有库存”
- python - 从中间向外循环列表
- html - 为什么浏览器只发送 4 个图像标签的 1 个请求?
- three.js - Threejs中未显示的点
- unity3d - 贝塞尔圆动画导出
- javascript - 无法使用对象访问读取数组中的属性