从文件 [java] 中读取不同的变量并将它们放入 JList

Read different variables from a file [java] and put them into a JList

我在编写应该能够从 .txt 文件中读取异构功能的代码时遇到了一些困难。 这是一个示例文件:

size=1.523763e-13 Type= aBc, KCd, EIf

我需要找到这个功能,然后将它们放在 netbeans 上的 Jlist 中。

为了找到大小变量,我想使用 BufferedReader class,但我不知道下一步该怎么做!

有什么帮助吗? 到目前为止我的代码:

public String findSize() {
    String spec = "";
    try {
        BufferedReader reader = new BufferedReader(new FileReader("sample.txt"));
        String line = reader.readLine();
        while(line!=null) {
            if (line.contains("size")) {
                for(int i = line.indexOf("size")+1, i = line.length(), i++)
                    spec +=...;

您可以通过 BufferedReaderScanner 拆分您读取的字符串,从而轻松做到这一点。

在下面的示例中,我使用了 Scanner 并正在阅读 System.in 中的行。您可以替换它以从源文件中读取行。

这是代码片段:

public static void main (String[] args)
{
    Scanner in = new Scanner(System.in);
    List<String> typeString;
    while(in.hasNext()) {
        String[] str = in.nextLine().split("=");
        System.out.println("Size: " + str[1].split(" ")[0] + " Type: " + str[2]);
        typeString = new ArrayList<>(Arrays.asList(str[2].split(", ")));
    }
}

请注意,这仅用于演示目的。您可以拆分字符串并使用子字符串并以任何方式存储它们。

输入:

size=1.523763e-13 Type=aBc, KCd, EIf

输出:

Size: 1.523763e-13 Type: aBc, KCd, EIf

typeString --> {aBc, KCd, EIf}