正如已经证明的那样,这种事情最好使用整数的二维数组列表 (ArrayList<ArrayList>>) 或整数的二维列表接口 (List<List<Integer>>)。这显然是要走的路,因为您不需要读取数据文本文件两次,一次是为了获取文件中的实际数据行数,一次是为了检索数据。通过使用像 ArrayList 或 List 这样的收集机制,您无需为它们分配大小,它们可以动态增长。但是,如果您仍然一心想要使用 2D 整数数组 (int[][]),那么您可以将集合完全转换为该数组。
这是我的想法(利用您提供的代码方案):
/**
* Allows the User to select a file using a file chooser navigation dialog.
* The selected file contents will then be placed into a 2D int Array. The
* file selected <u>must</u> contain 1 numerical value per text file Line,
* for example: <b>100100010</b>. Any blank lines in the file are ignored.<br>
*
* @param fileLocatedInFolder (Optional - String - Default is: "C:\") The
* directory path for where the JFileChooser lists files in when it opens.
* If nothing is supplied then the JFileChooser will start in the root
* directory of drive C.<br>
*
* @return (Two Dimensional int Array) A 2D int[][] array of the file contents.
* Each file line is an array row. Each numerical value in each file line is
* split into columnar digits for the 2D int array.
*/
public int[][] get2DArrayFromFile(String... fileLocatedInFolder) {
String fileChooserStartPath = "C:\\";
if (fileLocatedInFolder.length > 0) {
if (new File(fileLocatedInFolder[0]).exists() && new File(fileLocatedInFolder[0]).isDirectory()) {
fileChooserStartPath = fileLocatedInFolder[0];
}
}
JFileChooser fc = new JFileChooser(fileChooserStartPath);
fc.showDialog(this, "Open");
if (fc.getSelectedFile() == null) {
return null;
}
String filePath = fc.getSelectedFile().getAbsolutePath();
ArrayList<ArrayList<Integer>> rowsList = new ArrayList<>();
int[][] intArray = null;
// 'Try With Resources' use here to auto-close reader.
ArrayList<Integer> columnsList;
int row = 0;
int col = 0;
try (Scanner reader = new Scanner(fc.getSelectedFile())) {
String fileLine;
while (reader.hasNextLine()) {
fileLine = reader.nextLine();
fileLine = fileLine.trim(); // Trim the line
// If the file line is blank, continue to
// the next file line...
if (fileLine.isEmpty()) {
continue;
}
columnsList = new ArrayList<>();
col = 0;
String[] lineParts = fileLine.split("");
for (int i = 0; i < lineParts.length; i++) {
if (lineParts[i].matches("\\d")) {
columnsList.add(Integer.valueOf(lineParts[i]));
}
else {
System.err.println(new StringBuilder("Ivalid data detected ('")
.append(lineParts[i]).append("') on file line ")
.append((row + 1)).append(" in Column #: ").append((col + 1))
.append(System.lineSeparator()).append("Ignoring this data cell!")
.toString());
}
col++;
}
row++;
rowsList.add(columnsList);
}
}
catch (FileNotFoundException ex) {
Logger.getLogger("get2DArrayFromFile() Method Error!")
.log(Level.SEVERE, null, ex);
}
//Convert 2D Integer ArrayList to 2D int Array
intArray = new int[rowsList.size()][rowsList.get(0).size()];
for (int i = 0; i < rowsList.size(); i++) {
for (int j = 0; j < rowsList.get(i).size(); j++) {
intArray[i][j] = rowsList.get(i).get(j);
}
}
rowsList.clear();
return intArray;
}
并使用上述方法:
int[][] iBoard = get2DArrayFromFile();
// Display 2D Array in Console Window:
if (iBoard != null) {
for (int i = 0; i < iBoard.length; i++) {
System.out.println(Arrays.toString(iBoard[i]).replaceAll("[\\[\\]]", ""));
}
}
如果您的数据文件与您展示的一样:
000000
000000
001110
011100
000000
那么控制台窗口的输出将是:
0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0
0, 0, 1, 1, 1, 0
0, 1, 1, 1, 0, 0
0, 0, 0, 0, 0, 0