java - 如何将文本文件的行读入JavaFx中的数组
问题描述
我需要帮助阅读文本文件的内容并将每一行保存为数组中的字符串。例如,文本文件包含以下数据:
°C
12,0
21,9
我想将每一行读入一个数组,如:
line[0] = first_ine; //°C
line[1] = secondLine; //12,0
line[2] = thirdLine; //21,9
我的目标是能够访问我存储在数组中的任何行并将其内容打印在标签上,例如:
labelWithText.setText(line[0]);
行。这是我的代码的一个版本,我在其中尝试使用数组将文本文件的每一行存储在数组字段中。它会导致 ArrayOutOfBound 错误。
try {
input = new FileInputStream(new File("DataFiles/myData.txt"));
CharsetDecoder decoder = Charset.forName("ISO-8859-1").newDecoder();
decoder.onMalformedInput(CodingErrorAction.IGNORE);
InputStreamReader reader = new InputStreamReader(input, decoder);
BufferedReader buffReader = new BufferedReader(reader);
StringBuilder stringBuilder = new StringBuilder();
String line = buffReader.readLine();
int i = 0;
String lineContent[] = line.split("\n");
while(line != null) {
stringBuilder.append(line).append(System.getProperty("line.separator"));
line = buffReader.readLine();
lineContent[i] = line;
i++;
}
buffReader.close();
nomDataLabel.setText(lineContent[0]);
minDataLabel.setText(lineContent[1]);
maxDataLabel.setText(lineContent[2]);
} catch (Exception e) {
e.printStackTrace();
}
解决方案
平均 Joe 这里有两种加载 dictionary.txt 文件的方法
一种将数据放在 String[] 中,将另一种放在 ArrayList 字典
中 附带说明 Buffered Reader 比 Scanner 方法快 6 到 9 倍
对于数组列表:
ArrayList<String> dictionary = new ArrayList<>();
private void onLoad() throws FileNotFoundException, IOException {
long start2 = System.nanoTime();
try (BufferedReader input = new BufferedReader(new FileReader("C:/A_WORDS/dictionary.txt"))) {
for (String line = input.readLine(); line != null; line = input.readLine())
dictionary.add(line);
input.close();
}
对于一个简单的数组:
String[] simpleArray;
private void loadFile() throws FileNotFoundException, IOException {
File txt = new File("C:/A_WORDS/dictionary.txt");
try (Scanner scan = new Scanner(txt)) {
data = new ArrayList<>() ;
while (scan.hasNextLine())
data.add(scan.nextLine());
simpleArray = data.toArray(new String[]{});
int L = simpleArray.length;
System.out.println("@@@ L "+L);
}
}
推荐阅读
- python - 在保留某些节点的连通性的条件下打破有向图中的循环
- c++ - 函数模板:实例化和声明点
- html - 导航菜单最后一个孩子隐藏在第一个下拉菜单后面
- javascript - 使用 nodejs 应用程序中的 k8s 密钥
- javascript - 背景图像未加载到 div 中
- java - 删除所有空格和所有非字母字符。小写AZ的字符,转换为大写
- spring-boot - 如何将用户数据发送到不同的自定义 Spring Boot 应用程序进行身份验证?
- linux-kernel - 在 Raspberry Pi 3 的内核模块中禁用缓存?
- html - 根据选定的下拉菜单选项更改占位符文本的一部分
- angular - 如果文档已经存在,如何防止文档在 mongodb 中更新?