解释文本文件并将字符串用作变量

时间:2016-05-23 01:25:37

标签: java

public void readFile()
{
    while(fileReader.hasNext())
    {
        String blankClarification1 = fileReader.next();//Why Java Why?!
        Carthage_Independent_Status = Integer.parseInt(fileReader.next());
        String blankClarification2 = fileReader.next();
        Carthage_Stability = Integer.parseInt(fileReader.next());
        String blankClarification3 = fileReader.next();
        Carthage_Ruler_Name = fileReader.next();

基本文本文件解释。然而,我的问题是低效和耗时的吗?有没有办法从文本文件中取一个变量的名称,然后使它的值等同,使得变量不必在解释中具体命名(而是在前面声明),并且读者需要变量名称并将其设置为等于它旁边的值?

以下是文本文件

Carthage_Independent_Status 0
Carthage_Stability 100
Carthage_Ruler_Name Dido

当然还有更多内容,但有可能有这样的东西吗?

String Variable = fileReader.next();
String Value = fileReader.next();
Variable = Value;

有没有办法以这样的方式对它进行编程:它将Variable视为字符串,而不是作为变量,从而节省时间和精力?我已经看到了一些关于通过映射将字符串转换为变量的线程,但我尝试过的任何东西都没有达到预期的效果。我相信在PHP中有这样的方法,但是这又是Java。如果需要对问题作出任何澄清,我会很高兴我自己也很难说清楚自己。

1 个答案:

答案 0 :(得分:0)

  

问题:有没有办法从文本文件中获取变量的名称,然后使用它的值使它们等效,使得变量不必在解释中具体命名(而是在前面声明)读取器采用变量名称并将其设置为等于它旁边的值?`

是的,您可以使用Map<String, String>

  

问题:有没有办法对这种方式进行编程,使它看到Variable不是一个字符串,而是一个变量,从而节省了时间和精力?

1.如果您的变量基本上是基本类型或 String ,您可以使用一些util方法。喜欢

class Configuration {
  Map<String, String> properties; // load your files into this map at first

  public String get(String key) { // if the value is string type
    return properties.get(key);
  }

  public float getFloat(String key) { // if the value is float type
    if (properties.containsKey(key)) {
      return Float.parseFloat(properties.get(key));
    } else {
      return DEFAULT_VALUE; // the default value of the key "key"
    }
  }

  public int getInt(String key) { // if the value is int type
  }
}

有一个生产示例,请查看hadoop-common's Configuration.java

  1. 如果要将更复杂类型的变量保存到文件中,并从文件中读取变量,则需要序列化/反序列化工具包。 gson library将是一个良好的开端。您预先定义了Configuration类,只需将配置保存为json文件,然后从文件中加载Configuration类。