【问题标题】:How do I grab a specific sub-string of a file?如何获取文件的特定子字符串?
【发布时间】:2017-04-03 23:50:36
【问题描述】:

我有一个名为txt 的文档data.txt,其内容如下:

Account Name: Joe
  Account #: 50
  Account Balance: $105.0
  Check #: 110

我想解析上面的文件以获取: 的信息。例如,如果我要获取Account Name,我希望方法返回字符串Joe

我写了一个方法,get(String target),如下所示,它不能正常工作。

请注意target 是我想要获取其内部内容的字段。将上面的示例与Account Name 一起使用:

getValue("Account Name")(返回)"Joe"

public static String getValue(String target)
{
    File file = new File("data.txt");

    try
    {
        reader = new Scanner(file);
    } catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }

    String data = null;
    StringBuilder sb = new StringBuilder();

    while (reader.hasNextLine())
    {
        sb.append(reader.nextLine()); 
    }

    data = sb.toString().replaceAll("\\s+", "").trim().toLowerCase();

    String value = null;

    if (data.contains(target))
    {
        //stuck here
    }

    return value;
}

【问题讨论】:

    标签: java file substring


    【解决方案1】:
    // Call this method for a required target
    public static String getKey(String target) {
        Map<String, String> keyValueMap = loadKeyValueMap();
        return keyValueMap.get(target);
    }
    
    //load the keys and values only once from your input data file.
    public static Map<String, String> loadKeyValueMap()
    {
        File file = new File("data.txt");
        Scanner reader = null;
        try
        {
            reader = new Scanner(file);
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
    
        Map<String, String> map = new HashMap<>();
    
        while (reader.hasNextLine())
        {
            String nextLine = reader.nextLine();
            String[] split = nextLine.split(":");
            if (split.length() >= 2) map.put(split[0].trim(), split[1].trim());
            else break;
        }
        return map;
    }
    

    【讨论】:

    • 我在map.put(split[0].trim(), split[1].trim()); 或者更具体地说:split[1].trim() 上收到了IndexOutOfBoundsException
    • 原因是您的文件可能有一些空行。请检查以删除 data.txt 文件中的空行。或者作为替代方案,您可以在收到错误的行之前执行此操作。 if(split==null || split.length!=2) 继续;
    【解决方案2】:

    你可以试试这个:

    while (reader.hasNextLine()) {
            String text = reader.nextLine().trim();
            if (text.startsWith(target)) {
                String result = text.substring(target.length()+2);
                return result;
            }
        }
    

    剩下的你可以删除。

    你只需要在最后添加一个return语句,以防不匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多