java - 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] 之类的事情 - 它给出了一个错误,但是索引方法是至关重要的。
我怎么解决这个问题?
解决方案
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);
}
推荐阅读
- android - Android Firebase 用户创建
- python - 用一对多字典替换或映射 pandas 数据框列中的值
- php - 得到满足条件的更深的元素
- ios - ios 14 中的 .ply(多边形)格式文件问题
- javascript - 如何在 React 单元测试中插入真实的 File 对象以发挥作用
- javascript - 如何在 Chrome 上设置他人网站的断点?
- c# - CloudStorageAccount, making TableQuery request
- javascript - 无法通过迭代项目数据来形成结构并更新 currentTab 以外的值
- python - 如何在不指定角色确切名称的情况下赋予角色
- python - 提取字符串后的文本