gpt4 book ai didi

java - 如何将文件内容解析为变量?

转载 作者:行者123 更新时间:2023-11-29 06:57:36 26 4
gpt4 key购买 nike

我有这样的文本文件:

ABC=-1 Temp=2 Try=34 Message="some text" SYS=3
ABC=-1 Temp=5 Try=40 Message="some more and different text" SYS=6

模式继续,但只有“”内的数值和文本发生变化。

注意:Message= 也可以有多个引号

我想将ABC、Temp、Try 和SYS 的值存储到int 变量并将消息发送到字符串变量

我目前正在使用:

Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
int count = line.indexOf("ABC=");
if (count >= 0) {
int clear = line.charAt(count + 3);
}
}
scanner.close();

我想到了使用Scanner 类 并逐行读取,但我很困惑如何将行分类为不同的变量?

最佳答案

首先创建一个表示数据的类:

public static class MyData { // please pick a better name
final int abc;
final int temp;
final int tryNumber; // try is a keyword
final String message;
final int sys;

public MyData(int abc, int temp, int tryNumber, String message, int sys) {
this.abc = abc;
this.temp = temp;
this.tryNumber = tryNumber;
this.message = message;
this.sys = sys;
}
}

然后使用 Regex capture groups 创建一个将 String 转换为此类的方法:

private static Pattern p =
Pattern.compile("ABC=([^ ]+) Temp=([^ ]+) Try=([^ ]+) Message=\"(.+)\" SYS=([^ ]+)");

private static MyData makeData(String input) {
int abc = 0, temp = 0, tryNumber = 0, sys = 0;
String message = "";

Matcher m = p.matcher(input);
if (!(m.find()) return null;
abc = Integer.parseInt(m.group(1));
temp = Integer.parseInt(m.group(2));
tryNumber = Integer.parseInt(m.group(3));
message = m.group(4);
sys = Integer.parseInt(m.group(5));

return new MyData(abc, temp, tryNumber, message, sys);
}

然后使用扫描仪读取文件:

public static void main (String... args) throws Exception {
File file = new File("/path/to/your/file.txt");
List<MyData> dataList = new ArrayList<>();

Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
MyData data = makeData(line);
if(data != null) dataList.add(data);
}
scanner.close();
}

Here's a completely working demo on ideone

关于java - 如何将文件内容解析为变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31572815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com