繁体   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