如何将CSV数据加载到对象数组中并打印回用户?

9wbgstp7  于 2023-05-26  发布在  其他
关注(0)|答案(1)|浏览(106)

如何将CSV数据加载到对象数组中?
我已经想了很久了,我真的被卡住了。我是大学一年级的学生,在我的作业中,我必须使用CSV数据来生成统计数据,并将其打印回用户。在赋值规范中,它说我必须将文件中的数据加载到Project对象的数组中(“Project”是我的类之一)。老实说我不知道这是什么意思
因此,CSV文件包含与一个国家的项目相关的数据。我已经为“项目”对象设置了类字段,例如beneficiary、stage(例如:正在进行的,已完成的)和位置。我的任务之一是生成给定省份的统计数据。
我真的不知道如何将CSV数据加载到对象数组中。我在网上查过教程,所以我知道如何创建数组和其他东西;我只是不知道我应该如何加载CSV数据到它,然后收集它并将其打印回给用户。我已经从演讲幻灯片中收集了代码,但我所知道的就是简单地读取文件中的所有数据,并将其打印回用户。所以我已经把它记下来了,我只需要把数据加载到一个对象数组中,并为给定的省份生成统计数据。
以下是一些样本数据:

PROV_TERR_EN,BENEFICIARY_NAME_EN,BENEFICIARY_BAND_NBR,ASSET_CLASS_EN,PROJECT_NAME_EN,PROJECT_DESC_EN,PROJECT_STAGE_EN,LATITUDE,LONGITUDE,COORD_SYS

Saskatchewan,All Nations Healing Hospital,9999,Health,Design and construction of a new community health facility.,Design and construction of a new community health facility.,Completed,50.761877,-103.787043,GCS_North_American_1983_CSRS

Quebec,First Nations of Quebec and Labrador Sustainable Development Institute,9999,Energy sustainability and connectivity,Comprehensive Community Planning,Comprehensive community
import java.util.*;
import java.io.*;

public class Assignment {
    

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        int menuSelection;
        String region = null; 
        String path = "file_path"; // omitted for privacy
        
        readFile(path);
        

public static void readFile(String pFileName) { // Code from lecture slides; all I know how to do is print out all the data
    FileInputStream fileStream = null;
    InputStreamReader rdr;
    BufferedReader bufRdr;
    int lineNum;
    String line;
    try {
        fileStream = new FileInputStream(pFileName);
        rdr        = new InputStreamReader(fileStream);
        bufRdr     = new BufferedReader(rdr);
        lineNum    = 0;
        line       = bufRdr.readLine();
        String[] projectArray = new String[7];
        while(line != null) {
            lineNum++;
            processLine(line);
//            System.out.println(line);
            line = bufRdr.readLine();
                       
        }
            fileStream.close();
    }
    catch(IOException errorDetails) {
        if(fileStream != null) {
            try {
                fileStream.close();
            }
            catch(IOException ex2) { 
            }
        }
        System.out.println("Error in fileProcessing: " + errorDetails.getMessage());
    }
}

private static void processLine(String csvRow) {
    String[] splitLine;
    splitLine = csvRow.split(",");
    int lineLength = splitLine.length;
    
    for(int i = 0; i < lineLength; i++) {
        System.out.println(splitLine[i] + " ");
    }
    System.out.println("");
}

}
public class Project { // This is my Project class
    // Class Fields
    private String province;
    private String beneficiary;
    private int beneficiaryNum;
    private String assetClass;
    private String name;
    private String stage;
    private double location;
    
    // With Parameters Constructor
    public Project(String pProvince, String pBeneficiary, int pBeneficiaryNum, String pAssetClass, String pName, String pStage, double pLocation) {
        province = pProvince;
        beneficiary = pBeneficiary;
        beneficiaryNum = pBeneficiaryNum;
        assetClass = pAssetClass;
        name = pName;
        stage = pStage;
        location = pLocation;
    }
    
    // Copy Constructor
    public Project(Project pProject) {
        province = pProject.getProvince();
        beneficiary = pProject.getBeneficiary();
        beneficiaryNum = pProject.getBeneficiaryNum();
        assetClass = pProject.getAssetClass();
        name = pProject.getName();
        stage = pProject.getStage();
        location = pProject.getLocation();
    }
    
    // Default Constructor
    public Project() {
        province = "Province";
        beneficiary = "Beneficiary";
        beneficiaryNum = 12345678;
        assetClass = "Class";
        name = "Name";
        stage = "Stage";
        location = 00.00;
    }
    
    // Accessor Methods
    public String getProvince() {
        return province;
    }
    
    public String getBeneficiary() {
        return beneficiary;
    }
    
    public int getBeneficiaryNum() {
        return beneficiaryNum;
    }
    
    public String getAssetClass() {
        return assetClass;
    }
    
    public String getName() {
        return name;
    }
    
    public String getStage() {
        return stage;
    }
    
    public double getLocation() {
        return location;
    }
    
    // Mutator Methods
    public void setProvince(String pProvince) {
        province = pProvince;
    }
    
    public void setBeneficiary(String pBeneficiary) {
        beneficiary = pBeneficiary;
    }
    
    public void setBeneficiaryNum(int pBeneficiaryNum) {
        beneficiaryNum = pBeneficiaryNum;
    }
    
    public void setAssetClass(String pAssetClass) {
        assetClass = pAssetClass;
    }
    
    public void setName(String pName) {
        name = pName;
    }
    
    public void setStage(String pStage) {
        stage = pStage;
    }
    
    public void setLocation(double pLocation) {
        location = pLocation;
    }
    
    
    
    
    
}
gajydyqb

gajydyqb1#

首先需要计算文件中的行数。然后你就知道你需要的数组大小了。然后,您需要再次读取该文件以填充数组。下面是类Assignment的代码。我没有修改Project类的代码。
方法countLines计算文件中的行数。方法processFile通过为文件的每一行调用方法processLine来填充数组projects。注意,方法processFile不处理文件的第一行,因为该行包含头而不是数据。

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Assignment {
    private static int countFileLines(Path path) throws IOException {
        try (BufferedReader br = Files.newBufferedReader(path)) {
            int count = 0;
            String line = br.readLine();
            while (line != null) {
                count++;
                line = br.readLine();
            }
            return count;
        }
    }

    private static void processFile(Path path, Project[] projects) throws IOException {
        try (BufferedReader br = Files.newBufferedReader(path)) {
            String line = br.readLine();
            boolean first = true;
            int index = 0;
            while (line != null) {
                if (first) {
                    first = false;
                }
                else {
                    projects[index++] = processLine(line);
                }
                line = br.readLine();
            }
        }
    }

    private static Project processLine(String csvRow) {
        String[] fields = csvRow.split(",");
        Project project = null;
        if (fields.length == 7) {
            project = new Project(fields[0], // province
                                  fields[1], // beneficiary
                                  Integer.parseInt(fields[2]), // beneficiary num
                                  fields[3], // assets class
                                  fields[4], // name
                                  fields[5], // stage
                                  Double.parseDouble(fields[6])); // location
        }
        return project;
    }

    public static void main(String[] args) {
        try {
            Path path = Paths.get("datafile.csv");
            int count = countFileLines(path);
            Project[] projects = new Project[count];
            processFile(path, projects);
        }
        catch (IOException xIo) {
            xIo.printStackTrace();
        }
    }
}

相关问题