需要帮助从文件中获取数据以在构造函数中使用(Java)

时间:2016-02-25 01:55:42

标签: java

我试图摆脱硬编码信息,但我不确定如何做到这一点。这是我的代码:

import java.io.*;
public class Chemical {

    private String chemName;
    private String chemFreezingPoint;
    private String chemBoilingPoint;
    private String chemUnitNumbers;


    public Chemical(String name, String freezingPoint, String boilingPoint, String unitNumbers){
    chemName = name;
    chemFreezingPoint = freezingPoint;
    chemBoilingPoint = boilingPoint;
    chemUnitNumbers = unitNumbers;
    }

    Chemical Ethanol        = new Chemical("Ethanol",         "-173",   "172",   "1575");
    Chemical Oxygen         = new Chemical("Oxygen",          "-363",   "-306",  "1000");
    Chemical Water          = new Chemical("Water",           "32",     "212",   "5000");
    Chemical Benzene        = new Chemical("Benzene",         "41.9",   "176.2", "2750");
    Chemical EthyleneGlycol = new Chemical("Ethylene Glycol", "8.78",   "378",   "1900");

    public static String[][] returnArray(){
        String[][] chemArray = {{"Ethanol","-173","172","1575"},{"Oxygen","-363","-306","1000"},{"Water","32","212","5000"},
                {"Benzene","41.9","176.2","2750"},{"Ethylene Glycol","8.78","378","1900"}};
        return chemArray;
    }

}

我需要帮助的是用我从文本文件中获取的数据替换硬编码数据。我还需要使用我从已编码的2D数组中的文件中获取的数据,但我不确定如何做任何事情,因为我以前从未读过文件中的数据。任何帮助表示赞赏

2 个答案:

答案 0 :(得分:0)

要从文本文件中读取行,您可以使用BufferedReader类https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html,您可以使用readln();一次读取化学品及其信息的方法。另外,将字符串转换为沸点(e.t.c.)会更节省内存。对于整数,您可以为化学品的每个属性使用单独的数组。但是,这不应该是小型应用程序中的问题,例如

答案 1 :(得分:0)

假设您的文件格式如下:

ethanol,-173,172,1575
oxygen,-363,-306,1000
...

然后你可以这样做:

// Gotta put the file someplace
ArrayList<String> contents = new ArrayList<String>(0);

// Read the file into memory
String line;
BufferedReader bufferedReader = new BufferedReader(reader);
while ((line = bufferedReader.readLine()) != null) {
    contents.add(line);
}
bufferedReader.close();

// Create a dictionary (a HashMap) to hold the data
HashMap<String, Chemical> map = new HashMap<>();

// Load that Map with data
for (String line : contents) {
    String[] data = line.split(",")
    map.put(new Chemical(data[0], data[1], data[2], data[3]));
}