从文件中读取二维数组

我在文件’array.txt’中有一个2-D int数组。 我试图在二维数组中读取文件中的所有元素。 我在复制方面遇到问题。 它显示复制后所有元素值为’0’而不是原始值。 请帮帮我。 我的代码是:

import java.util.*; import java.lang.*; import java.io.*; public class appMainNineSix { /** * @param args */ public static void main(String[] args) throws java.io.FileNotFoundException{ // TODO Auto-generated method stub Scanner input = new Scanner (new File("src/array.txt")); int m = 3; int n = 5; int[][] a = new int [m][n]; while (input.next()!=null){ for (int i=0;i<m;i++){ for (int j=0;j<n;j++) a[i][j]= input.nextInt(); } } //print the input matrix System.out.println("The input sorted matrix is : "); for(int i=0;i<m;i++){ for(int j=0;j<n;j++) System.out.println(a[i][j]); } } } 

while (input.next()!=null)

这将消耗扫描仪输入流中的内容。 相反,尝试使用while (input.hasNextInt())

根据您希望代码的强大程度,您还应该在for循环中检查可以读取的内容。

 Scanner input = new Scanner (new File("src/array.txt")); // pre-read in the number of rows/columns int rows = 0; int columns = 0; while(input.hasNextLine()) { ++rows; Scanner colReader = new Scanner(input.nextLine()); while(colReader.hasNextInt()) { ++columns; } } int[][] a = new int[rows][columns]; input.close(); // read in the data input = new Scanner(new File("src/array.txt")); for(int i = 0; i < rows; ++i) { for(int j = 0; j < columns; ++j) { if(input.hasNextInt()) { a[i][j] = input.nextInt(); } } } 

使用ArrayLists的替代方法(无需预读):

 // read in the data ArrayList> a = new ArrayList>(); Scanner input = new Scanner(new File("src/array.txt")); while(input.hasNextLine()) { Scanner colReader = new Scanner(input.nextLine()); ArrayList col = new ArrayList(); while(colReader.hasNextInt()) { col.add(colReader.nextInt()); } a.add(col); } 

那么问题可能是你有一对嵌套循环来读取插入while循环中的数字。 为什么要在读完一次后重新读取数组值? 请注意,如果在最后一个数字之后文件中有任何内容 ,那么您将使用在文件结束后返回的任何.nextInt()填充数组!

编辑 – 井.nextInt()应该抛出一个exception,我想输入用完了,所以这可能不是问题。

开始简单……

更改:

 for (int j=0;j 

至:

 for (int j=0;j
		      	

问题是当你到达文件的末尾时,它会通过一个不存在usch元素的exception。

  public static void main(String[] args) { // TODO Auto-generated method stub try { Scanner input = new Scanner(new File("array.txt")); int m = 3; int n = 5; int[][] a = new int[m][n]; while (input.hasNextLine()) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { try{// System.out.println("number is "); a[i][j] = input.nextInt(); System.out.println("number is "+ a[i][j]); } catch (java.util.NoSuchElementException e) { // e.printStackTrace(); } } } //print the input matrix System.out.println("The input sorted matrix is : "); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { System.out.println(a[i][j]); } } } } catch (Exception e) { e.printStackTrace(); } } 

我知道在没有处理exception的情况下进行捕获但是临时工作。 请注意我将文件放在源文件夹之外。

你可以尝试使用Guava,

 public class MatrixFile { private final int[][] matrix; public MatrixFile(String filepath) { // since we don't know how many rows there is going to be, we will // create a list to hold dynamic arrays instead List dynamicMatrix = Lists.newArrayList(); try { // use Guava to read file from resources folder String content = Resources.toString( Resources.getResource(filepath), Charsets.UTF_8 ); Arrays.stream(content.split("\n")) .forEach(line -> { dynamicMatrix.add( Arrays.stream(line.split(" ")) .mapToInt(Integer::parseInt) .toArray() ); }); } catch (IOException e) { // in case of error, always log error! System.err.println("MatrixFile has trouble reading file"); e.printStackTrace(); } matrix = dynamicMatrix.stream().toArray(int[][]::new); }