java - 将文本文件中的数据保存到Java中的数组中
问题描述
我得到了这个调查结果的文本文件:
我已经设法让 Java 读取它并使用以下代码正常显示:
import java.io.*;
class Final {
public static void main (String [] args) throws Exception {
File file = new File ("C:\\Users\\loren\\Desktop\\t\\respuestas.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st=br.readLine()) !=null)
System.out.println(st);
}
}
但我不知道如何将它保存在二维数组上,有没有人有任何可能的解决方案?
解决方案
有很多方法可以做到这一点。为了有效地将文件内容放入二维 (2D) 数组中,您需要知道数组需要多大才能将所有内容正确放入其中,以免遇到生成ArrayOutOfBoundsException时的问题你填充那个数组。需要先确定数组的大小,然后才能将元素放入其中。需要考虑的事情是:
- 它是正确的文本文件吗?
- 文件中有多少有效数据行?
- 每行有多少列?
- 文件中是否有任何不需要的行(如标题行或空白行)?
这就是为什么使用 ArrayList、Map、HashMap 等收集机制是解决此问题的好方法。完成检索数据后,您始终可以将该集合转换为数组。
通过查看您的示例文件(嗯......它的图像:/),看起来有一个标题行,它简要描述了每个文件行中的每个数据列的用途。您没有指定是否希望它成为 2D 阵列的一部分。您也没有指定二维数组的数据类型,它是对象、字符串还是整数?
考虑到上述情况,我们必须假设您不希望将标题行放入数组中,而您只希望每行列中包含原始整数数据值。这然后回答了数组数据类型问题....整数(int)。
这是执行任务的一种方法:
public int[][] readDataFile(String filePath) throws FileNotFoundException {
ArrayList<int[]> list;
// Try with resources...Auto closes scanner
try (Scanner sRead = new Scanner(new File(filePath))) {
list = new ArrayList<>();
String line;
int lineCounter = 0;
while (sRead.hasNextLine()) {
line = sRead.nextLine().trim();
// Skip any blank lines
if (line.equals("")) { continue; }
lineCounter++;
// Is it a valid data file?
if (lineCounter == 1 && !line.startsWith("P1")) {
// No it's not!
JOptionPane.showMessageDialog(null, "Invalid Data File!",
"Invalid File!",
JOptionPane.WARNING_MESSAGE);
return null;
}
// Skip the Header Line
else if (line.startsWith("P1")) { continue; }
// Split the incomming line and convert the
// string values to int's
String[] strArray = line.split("\\s+");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
// Add to ArrayList
list.add(intArray);
}
}
// Convert the ArrayList to a 2D int Array
int[][] array = new int[list.size()][list.get(0).length];
for (int i = 0; i < list.size(); i++) {
System.arraycopy(list.get(i), 0, array[i], 0, list.get(i).length);
}
return array;
}
要使用这种方法,您可以使用:
try {
int[][] a = readDataFile("C:\\Users\\loren\\Desktop\\t\\respuestas.txt");
for (int[] a1 : a) {
System.out.println(Arrays.toString(a1));
}
} catch (FileNotFoundException ex) { ex.printStackTrace(); }
推荐阅读
- python - 尝试读取外部文件时,Igraph 没有此类属性错误
- reactjs - React formik 表单验证:如何最初禁用提交按钮
- c++ - 在 Visual Studio Code C++ MinGW 中运行时修改代码
- android - 确定 Android 中其他模块的 buildType
- javascript - 如果在某些情况下没有异步操作,JavaScript 是否可以在不等待第 n 行的情况下执行第 n+1 行代码?
- php - 无法重定向到控制器仪表板
- c# - 如何使用 c# 在 php 网页中浏览
- html - 不能在 div 内垂直居中 h1
- css - 媒体查询条件样式组件
- java - JAVA Spring Basic CRUD API 实现抛出错误