簡體   English   中英

逐字符讀取文本文件到2d char [] []數組中

[英]Reading text file character by character into a 2d char[][] array

我必須閱讀一個名為test.txt的文本文件。 文本文件的第一行是兩個整數。 這些整數告訴您2D char數組的行和列。 文件的其余部分包含字符。 該文件看起來有點像:4 4具有某些信息的文件,除了垂直彼此疊置而不是水平疊置。 然后,我必須使用嵌套的for循環將文件的其余所有內容讀取到2D char [] []數組中。 我不應該從一個數組復制到另一個數組。 這是我到目前為止的代碼。 我無法逐行將每個字符讀取到2D char數組中。 幫助工作了幾個小時。

    public static void main(String[] args)throws IOException 
{



    File inFile = new File("test.txt");                                 
    Scanner scanner = new Scanner(inFile);     
    String[] size = scanner.nextLine().split("\\s");         

    char[][] array = new char[Integer.parseInt(size[0])][Integer.parseInt(size[1])];

    for(int i=0; i < 4; i++) {
        array[i] = scanner.nextLine().toCharArray();
    }

    for(int k = 0; k < array.length; k++){
        for(int s = 0; s < array[k].length; s++){
            System.out.print(array[k][s] + " ");
        }
        System.out.println();
    }

     scanner.close();


}

}

如果我正確理解-文件格式類似

4 4
FILE
WITH
SOME
INFO

修改如下

    Scanner scanner = new Scanner(inFile);     
    String[] size = scanner.nextLine().split("\\s");         

    char[][] array = new char[Integer.parseInt(size[0])][Integer.parseInt(size[1])];

    for(int i=0; i < rows; i++) {
        array[i] = scanner.nextLine().toCharArray();
    }

上面的代碼用於初始化char數組。 為了打印相同的內容,您可以執行以下操作

Arrays.deepToString(array);

復制Tirath的文件格式:

4 4具有某些信息的文件

我將其傳遞到二維數組中,如下所示:

public static void main(String[] args){

    char[][] receptor = null;   //receptor 2d array
    char[] lineArray = null;    //receptor array for a line

    FileReader fr = null;
    BufferedReader br = null;
    String line = " ";

    try{
    fr = new FileReader("test.txt");
    br = new BufferedReader(fr);

        line = br.readLine();//initializes line reading the first line with the index
        int i = (int) (line.toCharArray()[0]-48); //we convert line to a char array and get the fist index (i) //48 = '0' at ASCII
        int j = (int)(line.toCharArray()[1]-48); // ... get the second index(j)

        receptor = new char[i][j];  //we can create our 2d receptor array using both index

        for(i=0; i<receptor.length;i++){
                line = br.readLine(); //1 line = 1 row
                lineArray = line.toCharArray(); //pass line (String) to char array
            for(j=0; j<receptor[0].length; j++){ //notice that we loop using the length of i=0
                receptor[i][j]=lineArray[j];    //we initialize our 2d array after reading each line
            }
        }

    }catch(IOException e){
        System.out.println("I/O error");
    }finally{
        try {
            if(fr !=null){
            br.close();
            fr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } //end try-catch-finally
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM