简体   繁体   English

从 .txt 文件中读取数据并保存为类变量

[英]Read data from .txt file and save as class variable

I'm trying to create a class called ExpectedProdInfo .我正在尝试创建一个名为ExpectedProdInfo的类。 This class will need to have many variables to store data, 182 to be exact.这个类需要有很多变量来存储数据,准确地说是 182 个。 I want to keep the data stored in a .txt file and call a method that will read the file line by line using the first line as the first class attribute and so on.我想将数据存储在.txt文件中,并调用一个方法,该方法将使用第一行作为第一类属性逐行读取文件,依此类推。

example: prod_info.txt contains:示例: prod_info.txt包含:

AAAA
BHJB
7657
.
.
.

Need to assign each line in order to a class attribute:需要为每一行分配一个类属性:

String attr1 = "AAAA";
String attr2 = "BHJB";
String attr3 = "7657";
.
.
.

If anyone new of a good way to achieve this while keeping the code easy to maintain I'd love to hear your solutions.如果有人在保持代码易于维护的同时实现这一目标的好方法是新的,我很乐意听到您的解决方案。

Check out the comments!看看评论! ! It's not a fully functioning Java code… kinda pseudo它不是一个功能齐全的 Java 代码……有点伪

import java.xyz ... // what's needed

public class ExpectedProductInfo {

  // define 182 class variables – Very bad approach!
  private String attr1;
  private String attr2;
  private String attr3;
  /*
  .
  .
  .
  */
  private String attr182;

  // good approach: an ordered collection: index 1 hold 1st variable and so on:
  ArrayList<String> attributes = new ArrayList<>(182);

  // A better approach: a Map based collection like HashMap. So you don't need
  // to follow the order of values, you can insert, get and manipulate them
  // consistently with their keys ...


  /**
   * reads a file and put each line in the collection
   * could be called on class instance or directly on the constructor
   * @param pathToFile path to file which contains the info line by line
   */
  private void readInfoFile(String pathToFile){
    File some = new File("some.txt");

    try {
      Scanner sc = new Scanner(some);

      while(sc.hasNextLine()){
        attributes.add(sc.nextLine());
      }
      sc.close();
    }
    catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  // Now the attributes contains each line as an element in order
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM