将文本文件逐字符读取到2d char[][]数组中



我必须读入一个名为test.txt的文本文件。文本文件的第一行是两个整数。这些整数告诉您2D char数组的行和列。文件的其余部分包含字符。该文件看起来有点像:4 4 file WITH SOME INFO,只是垂直地叠在一起,而不是水平地。然后,我必须使用嵌套的for循环将文件的其余内容读取到2D char[][]数组中。我不应该从一个数组复制到另一个数组。这是我目前掌握的代码。我在将每个字符逐行读取到2D字符数组中时遇到了问题。帮助已经为此工作了几个小时。

    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文件与一些信息

我会把它传递到一个2d数组中,如下所示:

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
}

最新更新