簡體   English   中英

將文本文件讀入二維數組

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

我需要將文本文件讀入二維數組,我可以完美地將文件讀入程序(請參閱下面的代碼),但是我無法理解如何將它們讀入二維數組。 函數正在讀入的數組是一個全局數組,因此為什么它不在函數中。

此外,我一開始不知道數組的行數(目前設置為 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;

    }

示例文本文件:

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

這里有幾個選項,但通常您會想要使用 JavaScanner 類,因為它專為此類事情而設計。 或者,使用現有的結構化數據格式(如 JSON 或 XML)和現有的解析器來配合它 - 優點是您可以使用大量處理這些格式的工具和庫,而不必重新-發明任何東西。

但是,通過掃描儀方法,它會是這樣的:

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;

}

如果你有固定的沒有。 您可以使用它的列數,但請確保輸入文件必須遵循相同的 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++;
            }
        }

下面是核心邏輯,你可能還想處理一些錯誤,比如一行被拆分成多少個元素,是否有空行等。

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]);

像這樣的東西會起作用

它不會只讀取二維文本文件..它應該適用於任何尺寸

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;
    }
}

我不是 Java 專家,但在 PHP 中我會用expand()來做。 但是我找到了一個例子,如何使用 string.split() 在 java 中做同樣的事情。 結果是一樣的……內容的二維數組。 如果可能,您應該嘗試向該文本文檔中的行添加分隔符。 但是您也可以拆分空格字符上的行。

例子:

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