简体   繁体   English

将文本文件读入二维数组

[英]Reading a text file into a 2D array

I need to read a text file into a 2D array, I can read files into the program perfectly fine (see my code below) however I cannot get my head around how to read them into a 2D array.我需要将文本文件读入二维数组,我可以完美地将文件读入程序(请参阅下面的代码),但是我无法理解如何将它们读入二维数组。 The array the function is reading into is a global array hence why it's not in the function.函数正在读入的数组是一个全局数组,因此为什么它不在函数中。

Also I won't know the amount of rows the array has at first (currently set at 300 as it won't be over this) and I know this could cause a problem, I've seen some people suggest using ArrayLists however I have to have a 2D array so I was also wondering if there was a way to change an ArrayList to a 2D array and if this would be more effective?此外,我一开始不知道数组的行数(目前设置为 300,因为它不会超过这个),我知道这可能会导致问题,我看到有些人建议使用 ArrayLists 但是我有有一个二维数组,所以我也想知道是否有办法将 ArrayList 更改为二维数组,这是否更有效?

 public static String readMaze(String fileName) {
        String line = null;

        try {
            FileReader fileReader = new FileReader(fileName);

            BufferedReader bufferedReader = new BufferedReader(fileReader);

            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);

                for (int i = 0; i < mazeNew.length; i++) {

                    for (int j = 0; j < mazeNew[i].length; j++) {
                        // mazeNew[i][j] = ; - this is where I think something needs to be added
                    }
                }
            }

            bufferedReader.close();

        }

        catch (FileNotFoundException ex) {
            System.out.println("Unable to open file: " + fileName);
        }

        catch (IOException ex) {
            System.out.println("Error reading file: " + fileName);
        }

        return fileName;

    }

example text file:示例文本文件:

11 4
5 6
4 6
0 5
3 5
8 7
1 4

There's a few options here, but generally you'll want to use the JavaScanner class as it's designed for exactly this kind of thing.这里有几个选项,但通常您会想要使用 JavaScanner 类,因为它专为此类事情而设计。 Alternatively, use an existing structured data format (like JSON or XML) and an existing parser to go with it - the advantage being you can make use of a vast amount of tools and libraries which deal with those formats and don't have to re-invent anything.或者,使用现有的结构化数据格式(如 JSON 或 XML)和现有的解析器来配合它 - 优点是您可以使用大量处理这些格式的工具和库,而不必重新-发明任何东西。

However, following through with the scanner approach, it would be like so:但是,通过扫描仪方法,它会是这样的:

public static ArrayList<int[]> readMaze(String fileName) {

    // Number of ints per line:
    int width=2;

    // This will be the output - a list of rows, each with 'width' entries:
    ArrayList<int[]> results=new ArrayList<int[]>();

    String line = null;

    try {
        FileReader fileReader = new FileReader(fileName);

        BufferedReader bufferedReader = new BufferedReader(fileReader);

        Scanner mazeRunner = new Scanner(bufferedReader);

        // While we've got another line..
        while (mazeRunner.hasNextLine()) {

            // Setup current row:
            int[] row = new int[width];

            // For each number..
            for (int i = 0; i < width; i++) {

                // Read the number and add it to the current row:
                row[i] = mazeRunner.nextInt();

            }

            // Add the row to the results:
            results.add(row);

            // Go to the next line (optional, but helps deal with erroneous input files):
            if ( mazeRunner.hasNextLine() ) {

                // Go to the next line:
                mazeRunner.nextLine();

            }

        }

        mazeRunner.close();

    }

    catch (FileNotFoundException ex) {
        System.out.println("Unable to open file: " + fileName);
    }

    catch (IOException ex) {
        System.out.println("Error reading file: " + fileName);
    }

    return results;

}

If you have fixed no.如果你有固定的没有。 of columns you can use this, but make sure input file must follow the same no of coulmns.您可以使用它的列数,但请确保输入文件必须遵循相同的 coulmns 数。

FileReader fileReader = new FileReader(fileName);

        Scanner sc = new Scanner(fileReader);
        int row=0, col=0;
        while ((sc.hasNext()) != null) {
            if(col < colSize){   //colSize is size of column
                mazeNew[row][col]= sc.nextInt();
            }
            else{
                col=0;
                row++;
            }
        }

Below is the core logic, you would probably also like to to handle some errors, such as how many elements is a line split into, are there empty lines, etc.下面是核心逻辑,你可能还想处理一些错误,比如一行被拆分成多少个元素,是否有空行等。

List<String[]> list = new ArrayList<>();
Pattern pattern = Pattern.compile("\\s+");
while ((line = bufferedReader.readLine()) != null) {
    list.add(pattern.split(line, -1));
}
String[][] mazeNew = list.toArray(new String[0][0]);

Something like this would work像这样的东西会起作用

it wont only read 2d text files .. it should work fine with any dimensions它不会只读取二维文本文件..它应该适用于任何尺寸

public class Utile{
    public static ArrayList<int[]> readMaze(String path){
        ArrayList<int[]> result = new ArrayList<>();
        try{
            Scanner sc = new Scanner(new File(path));
            String[] temp;
            String line;
            while(sc.hasNextLine()){
                line = sc.nextLine();
                if (line.length() != 0){ //if the line is empty it will cause NumberFormatException
                    temp = line.split(" ");
                    int[] val = new int[temp.length];
                    for(int i = 0;i < temp.length;i++){
                        val[i] = Integer.pareseInt(temp[i]);
                    }
                    result.add(val);
                }
            }
            
            sc.close();
            
        }catch(Exception e){
            e.printStackTrace(); //just log it for now
        }
        return result;
    }
}

I am not a java expert, but in PHP I would do it with explode() .我不是 Java 专家,但在 PHP 中我会用expand()来做。 But I found an example how to do the same in java using string.split().但是我找到了一个例子,如何使用 string.split() 在 java 中做同样的事情。 The result is the same ... an 2D Array of the content.结果是一样的……内容的二维数组。 If possible you should try to add an delimiter to the rows inside that text document.如果可能,您应该尝试向该文本文档中的行添加分隔符。 But you could split the rows on the space character either.但是您也可以拆分空格字符上的行。

Example:例子:

String foo = "This,that,other";
String[] split = foo.split(",");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
    sb.append(split[i]);
    if (i != split.length - 1) {
        sb.append(" ");
    }
}
String joined = sb.toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM