首页 > 解决方案 > Javafx:从文件中读取并使用 .split 方法拆分结果

问题描述

我想通过读取文件的数据来拆分基于 .split(",") 的结果,换句话说,对于这个特定的示例,我希望有 2 个索引,每个索引最多包含 5 个我也想访问的信息使用 .[0] 和 .[1] 方法。

带有数据的文件。

数据

文件读取方法。

public void fileReading(ActionEvent event) throws IOException {
    File file = new File("src/DateSpeicher/datenSpeicher.txt"); 
    BufferedReader br = new BufferedReader(new FileReader(file)); 
    String st; 
    while ((st = br.readLine()) != null) { 
        System.out.println(st); 
    }
}

该方法确实非常有效,但是我想知道如何将这两个拆分为两个索引或字符串数​​组,这两个数组都可以通过各自的索引 [0]、[1] 访问。对于固定数组中的第一个数据 - 第二个数组 [1][4] 中的最后一个数据为 655464 [0][0]。

我的方法: 1. 为每个 , 2. 添加数据直到 ","

问题:上面的 eventho 方法有效,你不能做诸如 array1[0] 之类的事情 - 它给出了一个错误,但是索引方法是至关重要的。

我怎么解决这个问题?

标签: javasplitfilereader

解决方案


Path path = Paths.get("src/DateSpeicher/datenSpeicher.txt"); // Or:
Path path = Paths.get(new URL("/DateSpeicher/datenSpeicher.txt").toURI());

两个字符串,然后处理它们:

String content = new String(Files.readAllBytes(path), Charset.defaultCharset());
String[] data = content.split(",\\R");

或列表列表:

List<String> lines = Files.readAllLines(path, Charset.defaultCharset());

// Result:
List<List<String>> lists = new ArrayList<>();

List<String> newList = null;
boolean addNewList = true;
for (int i = 0; i < lines.size(); ++i) {
    if (addNewList) {
        newList = new ArrayList<>();
        lists.add(newList);
        addNewList = false;
    }
    String line = lines.get(i);
    if (line.endsWith(",")) {
        line = line.substring(0, line.length() - 1);
        addNewList = true;
    }
    newList.add(line);
}

推荐阅读