首页 > 解决方案 > Java - 读取文本文件并添加唯一 ID

问题描述

我正在尝试学习 Java,并且在我遇到的部分问题上真的很挣扎。我被要求编写一个方法来读取一个文本文件,其中每一行代表一个对象的实例,例如 SalesPerson

问题是要求我为读入的每一行添加一个标识符 id,该 id 不存在于文本文件中。我在我的销售人员类中声明了一个带有构造函数和 getter 和 setter 方法的 id,并让我的方法在另一个类中读取下面的文本文件。但是它不起作用,我不确定我哪里出错了。有人可以给我一个指针..吗?我会很感激。,

public static Collection<SalesPerson> readSalesData() {
    String pathname = CXU.FileChooser.getFilename();
    File aFile = new File(pathname);
    Scanner bufferedScanner = null;
    Set<SalesPerson> salesSet = new HashSet<>();

    try {
        int id;
        String name;
        String productCode;
        int sales;
        int years;
        Scanner lineScanner;
        String currentLine;
        bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));

        while(bufferedScanner.hasNextLine()) {
            currentLine = bufferedScanner.nextLine();
            lineScanner = new Scanner(currentLine);
            lineScanner.useDelimiter(",");
            id = salesPerson.getId();
            name = lineScanner.next(); //return the next token as a string
            years = lineScanner.nextInt();
            productCode = lineScanner.next(); // return the next token as a string
            sales = lineScanner.nextInt(); // return the next token as a double
            salesSet.add(new SalesPerson(id, name, years, productCode, sales));   
        }
    }
    catch (Exception anException) {
        System.out.println("Error: " + anException);
    }
    finally { 
        try {
            bufferedScanner.close();
        }
        catch (Exception anException) {
            System.out.println("Error: " + anException);
        }
    }
    return salesSet;
}


\\Constructor from Class SalesPerson
public SalesPerson(int aId, String aname, int aYears, String aProductCode, int aSales) {
    super(); // optional
    this.id = ++nextId;
    this.name = aname;
    this.years = aYears;
    this.productCode = aProductCode;
    this.sales = aSales;
}


标签: java

解决方案


请检查以下代码,我试图让事情变得更简单:

package com.project;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public class Temp {

    public static void main(String[] args) {
        Set<SalesPerson> salesPersons = (Set<SalesPerson>) readSalesData();

        System.out.println(salesPersons.toString());
    }

    public static Collection<SalesPerson> readSalesData() {
        Set<SalesPerson> salesPersons = new HashSet<>();

        try {
            File file = new File("D:/file.txt");
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.isEmpty())
                    break;

                String[] rowData = line.split(";");
                salesPersons.add(new SalesPerson(rowData[0].trim(), Integer.parseInt(rowData[1].trim()), rowData[2].trim(), Integer.parseInt(rowData[3].trim())));
            }

            fileReader.close();
        } catch (Exception ex) {
            System.out.println(ex);
        }

        return salesPersons;
    }
}


package com.project;

public class SalesPerson {

    // Static to keep reserve value with each new instance
    private static int AUTO_ID = 1;

    private int id;
    private String name;
    private int years;
    private String productCode;
    private int sales;

    public SalesPerson() {

    }

    public SalesPerson(String name, int years, String productCode, int sales) {
        this.id = AUTO_ID;
        this.name = name;
        this.years = years;
        this.productCode = productCode;
        this.sales = sales;

        AUTO_ID++;
    }

    // Getters & Setters...

    @Override
    public String toString() {
        return "ID: " + id + ", Name: " + name + ", Years: " + years + ", Product Code: " + productCode + ", Sales: " + sales + System.lineSeparator();
    }
}

这是我的数据文件:

FullName1 ; 20; p-code-001; 10
FullName2 ; 30; p-code-002; 14
FullName3 ; 18; p-code-012; 1040

推荐阅读