【问题标题】:Javafx: Reading from an File and Spliting the result with .split methodJavafx:从文件中读取并使用 .split 方法拆分结果
【发布时间】:2020-01-13 15:50:21
【问题描述】:

我想通过读取文件的数据来拆分基于 .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.为每个创建一个ArrayList, 2.添加数据直到","

问题:即使上述方法有效,您也不能执行 array1[0] 之类的操作 - 它会报错,但索引方法很重要。

我该如何解决这个问题?

【问题讨论】:

  • 使用 Java 11+:String[] arr = Files.readString​(Paths.get("src/DateSpeicher/datenSpeicher.txt")).split(","); --- 基本上,将整个文本文件读入字符串,然后调用split(",")。如果您需要在 Java 10 或更早版本上将整个文本文件读入内存,请进行网络搜索。
  • [] 是一个运算符,而不是一个方法,它只适用于数组。 array[i] 的等效列表是 list.get(i),在这种情况下,如果您不想多次读取整个文件,您确实需要列表,因为您事先不知道逗号的数量(除非您想要实现这个基本上是自己重新实现ArrayList的逻辑。

标签: java split filereader


【解决方案1】:
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);
}

【讨论】:

  • 不确定我是否会保留布尔值;您可以简单地使用newList == null 作为检查并将addNewList = true; 替换为newList = null;;此外,您的两种方法都将整个文件读入内存,从而导致不必要的高内存消耗。 BufferedReader+while 对我来说似乎比将所有行都读到List...