【发布时间】: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;
}
【问题讨论】: