如何从记事本文本文件中获取数据并创建Java对象集合?

如何从记事本文本文件中获取数据并创建Java对象集合?,java,object,collections,text-files,Java,Object,Collections,Text Files,我有一个包含客户数据的记事本文件, 每一行都有一个新客户: 我只想从记事本文件(如下所示)中获取数据,将每个客户保存在java对象中,并将每个对象保存在客户列表中 Print_Sequence|Indication|SP/N-SP |Bill_Type |Region|Cluster 00001 |Ordinary | |Notice Bill| | C10 00002 |Ordinary | |Not

我有一个包含客户数据的记事本文件, 每一行都有一个新客户:

我只想从记事本文件(如下所示)中获取数据,将每个客户保存在java对象中,并将每个对象保存在客户列表中

Print_Sequence|Indication|SP/N-SP    |Bill_Type  |Region|Cluster
00001         |Ordinary  |           |Notice Bill|      | C10
00002         |Ordinary  |           |Notice Bill|      | C20
00003         |Ordinary  |           |Notice Bill|      | C30
我从文件中获取了字符串变量中的数据:

String details = "";
KE_Globals.dataFile = fileChooser.getSelectedFile().getAbsoluteFile();
Scanner input = new Scanner(KE_Globals.dataFile);

while (input.hasNextLine()) {
    details += input.nextLine()+System.getProperty("line.separator");
}
现在,我想将数据转换成以下Java类:Customer

public class Customer {

private String Print_Sequence = null;
private String Indication = null;
private String SPN_SP = null;
private String Bill_Type = null;
private String Region = null;
private String Cluster = null;

public Customer(String print_Sequence, String indication, String sPN_SP, String bill_Type, String region, String cluster) {
    Print_Sequence = print_Sequence;
    Indication = indication;
    SPN_SP = sPN_SP;
    Bill_Type = bill_Type;
    Region = region;
    Cluster = cluster;
}

public String getPrint_Sequence() {
    return Print_Sequence;
}

public void setPrint_Sequence(String print_Sequence) {
    Print_Sequence = print_Sequence;
}

public String getIndication() {
    return Indication;
}

public void setIndication(String indication) {
    Indication = indication;
}

public String getSPN_SP() {
    return SPN_SP;
}

public void setSPN_SP(String sPN_SP) {
    SPN_SP = sPN_SP;
}

public String getBill_Type() {
    return Bill_Type;
}

public void setBill_Type(String bill_Type) {
    Bill_Type = bill_Type;
}

public String getRegion() {
    return Region;
}

public void setRegion(String region) {
    Region = region;
}

public String getCluster() {
    return Cluster;
}

public void setCluster(String cluster) {
    Cluster = cluster;
}

}
谁能告诉我怎么做?比如:

List customers=new ArrayList();
客户c=新客户();
c、 设置属性。。。。
加上(c);

谢谢。

假设这是
00001 |普通| | |通知单| | C10
文件中的客户记录,然后根据
管道拆分行

List<Customer> customers = new ArrayList<Customer>();
while (input.hasNextLine()) {
String customeRecord = input.nextLine().split("[|]");  //or  \\|

Customer record = new Customer(customeRecord[0],customeRecord[1],customeRecord[2],customeRecord[3],customeRecord[4],customeRecord[5]);

 //finally add this customer object to List
  customers.add(record);
}
List customers=new ArrayList();
while(input.hasNextLine()){
字符串customerRecord=input.nextLine().split(“[|]]”;//或\\|
客户记录=新客户(客户记录[0]、客户记录[1]、客户记录[2]、客户记录[3]、客户记录[4]、客户记录[5]);
//最后将此客户对象添加到列表中
添加(记录);
}

注意:当您根据管道
拆分字符串
00001 |普通| | |注意比尔| | C10
时,每个部分都会有一些空格,您需要修剪空格以获得准确的值,如果第一行是标题,您也需要忽略它,这里有一种方法可以做到:迭代文件中的所有行,从每一行解析一个
客户
,其中解析包括将行拆分为由
|
分隔的字段,并去除空白

public static void main(String[] args) {
    // ...
    KE_Globals.dataFile = fileChooser.getSelectedFile().getAbsoluteFile();
    List<Customer> customers = new ArrayList<>();
    Scanner input = new Scanner(KE_Globals.dataFile);
    while (input.hasNextLine()) {
        String customerRecord = input.nextLine();
        customers.add(Customer.parseFromRecord(customerRecord));
    }
}

看起来你已经知道如何读取文件中的行了,所以我假设你能够做到这一点

假设你有一行文件;由于它们的格式都相同,这使得这项任务更容易

比如说: 字符串s=input.nextLine()

然后,使用字符串#split(“|”)可以轻松地将该字符串的不同部分解析为我们想要的部分。假设我们有一条线:

"00001         |Ordinary  |           |Notice Bill|      | C10"
然后,如果这是通过执行input.nextLine()接收到的输入,我们可以调用s.split(“|”),这将为我们提供一个包含以下字符串的数组:

String[] array = {"00001         ","Ordinary  ","           ","Notice Bill","      "," C10"};
String还有一个很好的方法,名为String#trim(),它将删除任何前导空格和任何结尾空格(空格、制表符等)

因此,对于数组中的每个字符串,我们可以修剪输入,这将为我们提供:

So now, we have that array = {"00001","Ordinary","","Notice Bill","","C10"}.
现在我们有了一些可以轻松使用的东西。假设持有相同的订单(事实如此),我们可以说:

Customer c = new Customer(array[0], array[1], array[2], array[3], array[4], array[5]);
结合所有这些,我们可以做以下工作(摘自您的代码):

while(input.hasNextLine()){
字符串nextInput=input.nextLine();
String[]pI=nextInput.split(\\\\;”;//pI代表可解析输入,请转义管道字符(“|”),因为它在Java中是一个特殊字符。
对于(inti=0;i
为了便于阅读,我以更详细的方式写了这篇文章。这应该适用于每一行,因为它们每次的样式都相同。如果需要,还可以为客户将空字符串表示为“null”,这可能有助于清理代码

希望这有帮助

编辑:为清晰起见,在字符串中添加了引号。

请检查此方法

List<Customer> customers = new ArrayList<Customer>();
String [] arr = new String[6];

   while (input.hasNextLine()) {                   
    arr =  input.nextLine().split("\\|");
    Customer customer = new Customer(arr[0],arr[1],arr[2],arr[3]arr[4],arr[5])
    customers.add(customer);

}
值得一提的是,“|”在java中是一个特殊的字符,您需要输入“\\\\”来识别它


以下是从文本文件获取客户数据并填充到
列表
集合的方法:

import java.util.*;
import java.io.*;
import java.nio.file.*;

public class CustomerExtraction {

    public static void main(String [] args)
            throws IOException {

        Path file = Paths.get("customer_data.txt");
        List<String> lines = Files.readAllLines(file);
        List<Customer> customers = new ArrayList<>();

        for (int i = 1; i < lines.size(); i++) {
            String [] fields = lines.get(i).split("\\|");
            Customer cust = new Customer(fields[0].trim(), fields[1].trim(), fields[2].trim(), fields[3].trim(), fields[4].trim(), fields[5].trim());
            System.out.println(cust); // print to console for verification
            customers.add(cust);
        }
    }
}

class Customer {

    private String printSequence;
    private String indication;
    private String spnSp;
    private String billType;
    private String region;
    private String cluster;

    public Customer(String printSequence, String indication, String spnSp, String billType, String region, String cluster) {
        this.printSequence = printSequence;
        this.indication = indication;
        this.spnSp = spnSp;
        this.billType = billType;
        this.region = region;
        this.cluster = cluster;
    }

    // get and set methods as required here ...

    @Override
    public String toString() {
        return String.join(", ", printSequence, indication, spnSp, billType, region, cluster);
    }
}
这将迭代列表中的所有行(不包括第一行,即列标题)

后面的代码是从字符串数组中的
String
字段创建
Customer
对象。
String
类的
trim()
方法删除每个字段开头和结尾的空格。然后,将每个客户添加到
列表中


关于
客户的注释
类别:

  • 无需将实例变量
    String
    s初始化为
    null
    ;默认情况下,它们是
    null
  • 变量名必须是camelCase(不以大写开头)且不带下划线
  • 变量SPN_SP:按照惯例,只有常量(静态字段和最终字段)用大写字母表示

OP:不要自动创建getter和setter-您需要它们吗?不,你没有。通过构造函数传递所需的所有参数。@Nikolas I共有408个字段,最大参数数为255个。我想我们不能通过所有的参数。请建议一个对象中的字段不应超过5个(这些数字各不相同,但都很小)。408绝对是疯了,设计也很糟糕。将对象分解为较小的对象。请忘记这样想,先读一些关于面向对象设计的书或文章。你所做的是错误的。我总共有408个字段,所以问题是我们传递的构造函数参数不能超过255个。然后请提出你这是什么意思?你能再澄清一点吗?就像你把6个参数传递给构造函数
Customer c=new Customer(数组[0]、数组[1]、数组[2]、数组[3]、数组[4]、数组[5])因此,我们不能传递超过255个参数,但我要传递408个字段。我无法想象一个具有408个不同参数的构造函数有什么用途,但如果是这样的话,您可以创建一个新客户,而不传递任何字段,然后有2个(非常大的)setter方法,两个都有204个方法,尽管这令人难以置信,太过分了,我劝你再确认一下
while (input.hasNextLine()) {
    String nextInput = input.nextLine();
    String[] pI = nextInput.split("\\|"); //pI stands for parseableInput, escape the pipe character ('|') since it's a special char in Java.
    for(int i = 0; i < nextInput.length; i++) { //trim all of the input
        pI[i] = pI[i].trim();
    }
    Customer next = new Customer(pI[0], pI[1], pI[2], pI[3], pI[4], pI[5]);
    customers.add(next);
}
List<Customer> customers = new ArrayList<Customer>();
String [] arr = new String[6];

   while (input.hasNextLine()) {                   
    arr =  input.nextLine().split("\\|");
    Customer customer = new Customer(arr[0],arr[1],arr[2],arr[3]arr[4],arr[5])
    customers.add(customer);

}
for(Customer c: customers){
    System.out.println(c.toString());
}
import java.util.*;
import java.io.*;
import java.nio.file.*;

public class CustomerExtraction {

    public static void main(String [] args)
            throws IOException {

        Path file = Paths.get("customer_data.txt");
        List<String> lines = Files.readAllLines(file);
        List<Customer> customers = new ArrayList<>();

        for (int i = 1; i < lines.size(); i++) {
            String [] fields = lines.get(i).split("\\|");
            Customer cust = new Customer(fields[0].trim(), fields[1].trim(), fields[2].trim(), fields[3].trim(), fields[4].trim(), fields[5].trim());
            System.out.println(cust); // print to console for verification
            customers.add(cust);
        }
    }
}

class Customer {

    private String printSequence;
    private String indication;
    private String spnSp;
    private String billType;
    private String region;
    private String cluster;

    public Customer(String printSequence, String indication, String spnSp, String billType, String region, String cluster) {
        this.printSequence = printSequence;
        this.indication = indication;
        this.spnSp = spnSp;
        this.billType = billType;
        this.region = region;
        this.cluster = cluster;
    }

    // get and set methods as required here ...

    @Override
    public String toString() {
        return String.join(", ", printSequence, indication, spnSp, billType, region, cluster);
    }
}
List<String> lines = Files.readAllLines(file);
for (int i = 1; i < lines.size(); i++) {
String [] fields = lines.get(i).split("\\|");