如何从文件中检索指定的数据?

发布于 2024-12-04 09:28:13 字数 415 浏览 5 评论 0原文

我将此数据存储在 .dat 文件中:

data = date + ": " + y + "L/100KM "+ " " + value1 + "dt "+ value2 + "KM\n";

每一行都有不同的日期、y、value1 和 value2 值。 我想检索每一行的变量 value1 。如何浏览文件并提取所有行的这个变量。我在我的项目中陷入了这个问题。谢谢你的帮助。 编辑:示例: 我在文件中存储了这 3 个数据:

11/09: 5.8L/100KM 20dt 250KM
12/09: 6.4L/100KM 60dt 600KM
13/09: 7.5L/100KM 50dt 543KM

在这种情况下,我想检索 20dt、60dt 和 50dt。

I'm storing this data in a .dat file:

data = date + ": " + y + "L/100KM "+ " " + value1 + "dt "+ value2 + "KM\n";

Every line has different values of date,y,value1 and value2.
I want to retrieve variable value1 of every line. How to browse the file and extract this variable of all lines. I'm stucking in this problem in my project. Thanks for helping.
EDIT: Example:
I have this 3 datas stored in the file:

11/09: 5.8L/100KM 20dt 250KM
12/09: 6.4L/100KM 60dt 600KM
13/09: 7.5L/100KM 50dt 543KM

In that case, i want to retrieve 20dt, 60dt and 50dt.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怀中猫帐中妖 2024-12-11 09:28:13

这是使用正则表达式的一个建议:

String line = "12/09: 6.4L/100KM 60dt 600KM";

Pattern p = Pattern.compile("(\\d+)dt");
Matcher m = p.matcher(line);

if (m.find())
    System.out.println(m.group(1));   // prints 60

如果您有几行要迭代,您可以使用 new BufferedReader(new FileReader("youfile.dat")) 并执行类似的操作

String line;
while ((line = br.nextLine()) != null) {
    Matcher m = p.matcher(line);
    if (m.find())
        process(m.group(1));
}

您也可以只需使用 line.split(" ") 并选择第 3:rd 元素:

String line = "12/09: 6.4L/100KM 60dt 600KM";
String dtVal = line.split(" ")[2];

// Optional: Remove the "dt" part.
dtVal = dtVal.substring(0, dtVal.length() - 2);

System.out.println(dtVal);

Here's one suggestion using regular expressions:

String line = "12/09: 6.4L/100KM 60dt 600KM";

Pattern p = Pattern.compile("(\\d+)dt");
Matcher m = p.matcher(line);

if (m.find())
    System.out.println(m.group(1));   // prints 60

If you have several lines to iterate over, you'd use for instance a new BufferedReader(new FileReader("youfile.dat")) and do something like

String line;
while ((line = br.nextLine()) != null) {
    Matcher m = p.matcher(line);
    if (m.find())
        process(m.group(1));
}

You could also just use line.split(" ") and select the 3:rd element:

String line = "12/09: 6.4L/100KM 60dt 600KM";
String dtVal = line.split(" ")[2];

// Optional: Remove the "dt" part.
dtVal = dtVal.substring(0, dtVal.length() - 2);

System.out.println(dtVal);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文