java 如何将txt文件读入二维数组Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35147544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:48:01  来源:igfitidea点击:

How to read a txt file into a 2d Array Java

javaarraysmultidimensional-arraytry-catchfilereader

提问by

Quick question, how would I go about reading a txt file into a 2d array? I need to but each line into an array in order to later on use it for measuring summation of length and width. This will be used for the game of life.

快速提问,我将如何将 txt 文件读入二维数组?我需要将每一行都放入一个数组中,以便稍后使用它来测量长度和宽度的总和。这将用于生命的游戏。

CODE

代码

public P4_Icel_Murad_Life(String fileName) {
        Scanner in;
        try {
            Scanner s = new Scanner(new File("C:/Users/muro0/Desktop/life100.txt"));
            int matrix[][] = new int[size][size];
            while (s.hasNext()) {
                for (int i = 0; i < matrix.length; i++) {
                       for (int col = 0; col < matrix.length; col++) {
                      //      matrix[i][col] = ;
                        }
                }
            }
            s.close();

        } catch (IOException i) {
            System.out.println("Problems..");

        }
    }

TEXT DOCUMENT

文本文件

20 20
    0    2
    0    6
    0    7
    0   10
    0   11
    0   16
    1    0
    1    4
    1    7
    2    6
    2   12
    2   15
    2   19
    3    0
    3    4
    3   14
    3   16
    3   17
    4    0
    4    8
    4   12
    4   14
    4   15
    5    0
    5    2
    5    4
    5    7
    5   13
    5   17
    6   11
    6   14
    6   15
    6   18
    7    4
    7   10
    7   13
    7   14
    8    6
    8   11
    8   12
    8   14
    8   17
    8   19
    9    6
    9    8
    9   13
    9   14
   10    3
   10   10
   10   19
   11    6
   11    7
   11    9
   11   10
   11   17
   12    0
   12    2
   12   12
   13    0
   13    1
   13    7
   13    8
   13   14
   13   15
   14    7
   14    9
   14   12
   14   13
   14   16
   14   18
   15    0
   15    2
   15    6
   15    8
   15   10
   15   11
   15   16
   15   17
   16    2
   16    3
   16   18
   17    2
   17    7
   17   11
   17   13
   17   19
   18    0
   18    5
   18    6
   18   11
   18   12
   18   13
   18   14
   19    3
   19    4
   19    6
   19    8
   19   11
   19   16
   19   17

采纳答案by Wisienkas

So it seems that the textfile contain all pairs at which where is life in the game of life.

因此,文本文件似乎包含生命游戏中生命所在的所有对。

What you do is increase the "i" value for each read, but that is not garanteed.

您所做的是为每次读取增加“i”值,但这不是保证。

Instead the following protocol is the one of the text file it seems.

相反,以下协议似乎是文本文件之一。

  1. Line contain the X and Y size of the board.
  1. 线包含板的 X 和 Y 尺寸。

The rest of the lines contains spots where there is life.

其余的线条包含有生命的地方。

So your code should look more like this(not included exception handling apart from what you already provided)

所以你的代码应该看起来更像这样(除了你已经提供的不包括异常处理)

 public P4_Icel_Murad_Life(String fileName) {
        Scanner in;
        try {
            Scanner s = new Scanner(new File("C:/Users/muro0/Desktop/life100.txt"));
            int rows = s.nextInt();
            int columns = s.nextInt();
            int matrix[][] = new int[rows][columns];
            while (s.hasNextInt()) {
                int row = s.nextInt();
                int col = s.nextInt(); // If this fails the text documnet is incorrect.
                matrix[row][col] = 1;
            }
            s.close();
            // At this point all dead cells are 0 and all live are 1
        } catch (IOException i) {
            System.out.println("Problems..");

        }
    }

回答by David Mumladze

public int[][] P4_Icel_Murad_Life(String fileName) {
    try {
        BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));

        // n = Rownum ; m = Colnum
        int array[][] = new int[n][m];
        String line = reader.readLine();

        int i = 0, j = 0;
        while (line != null) {
            String strArray[] = line.split(" ");

            if (!line.trim().isEmpty()) {
                for (String s : strArray) {
                    if (!s.trim().isEmpty()) {
                        array[i][j++] = Integer.parseInt(s);
                    }
                }
                line = reader.readLine();
                i++;
                j = 0;
            }
        }
        reader.close();
        return array;
    } catch (IOException ex) {
        System.out.println("Problems..");
    }
    return null;
}

回答by v.ladynev

You can use opencsvto read and write such kind of a file

您可以使用opencsv读取和写入此类文件

 CSVReader reader = new CSVReader(
                new FileReader("C:/Users/muro0/Desktop/life100.txt"), ' ');
 // Read all rows at once
 List<String[]> allRows = readAll(reader);

It reads file to strings, but you can convert it to integers of course.

它将文件读取为字符串,但您当然可以将其转换为整数。

回答by Arnaud

You are interested in intvalues, so use this.

您对int值感兴趣,因此请使用它。

Also, the hasNextLinecondition has been moved into the rowsloop, and a hasNextIntcondition added to the columnsloop.

此外,hasNextLine条件已移动到循环中,并将hasNextInt条件添加到循环中。

public P4_Icel_Murad_Life(String fileName) {
        Scanner in;
        try {
            Scanner s = new Scanner(new File("C:/Users/muro0/Desktop/life100.txt"));
            int matrix[][] = new int[size][size];

                for (int i = 0; i < matrix.length && s.hasNextLine(); i++) {
                       for (int col = 0; col < matrix.length && s.hasNextInt(); col++) {
                           matrix[i][col] = s.nextInt() ;

                        }
                       s.nextLine(); // col values populated for this row, time to go to the next line
                }

            s.close();

        } catch (IOException i) {
            System.out.println("Problems..");

        }
    }