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

时间:2018-10-25 12:56:45

标签: java

我正在尝试创建一个名为ExpectedProdInfo的类。此类将需要具有许多变量来存储数据,确切地说是182。我想将数据存储在.txt文件中,并调用一个方法,该方法将第一行用作第一类属性来逐行读取文件,依此类推。

示例:prod_info.txt包含:

AAAA
BHJB
7657
.
.
.

需要将每行分配给一个类属性:

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

如果有新手在保持代码易于维护的同时实现此目标的好方法,我很乐意听到您的解决方案。

1 个答案:

答案 0 :(得分:0)

查看评论! 这不是功能齐全的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
  }

}