将文件读取为二维字符数组

Reading a file as a 2d char array

如何仅使用 java.io.FileScanner 和文件未找到异常将仅包含 chars 的文本文件中的数据读入二维数组?

这是我尝试使用的方法,它将文件读入二维数组。

public AsciiArt(String filename, int nrRow, int nrCol){
    this.nrRow = nrRow;
    this.nrCol = nrCol;

    image = new char [nrRow][nrCol];

    try{
        input = new Scanner(filename);

        while(input.hasNext()){

        }   
    }
}

粗略的做法是:

    File inputFile = new File("path.to.file");
    char[][] image = new char[200][20];
    InputStream in = new FileInputStream(inputFile);
    int read = -1;
    int x = 0, y = 0;
    while ((read = in.read()) != -1 && x < image.length) {
        image[x][y] = (char) read;
        y++;
        if (y == image[x].length) {
            y = 0;
            x++;
        }
    }
    in.close();

不过我相信还有其他方法会更好、更有效,但你明白了原理。

确保您正在导入 java.io.*(或您需要的特定 classes,如果这是您想要的)以包含 FileNotFoundException class。显示如何填充二维数组有点困难,因为您没有指定要如何准确解析文件。但是这个实现使用了 Scanner、File 和 FileNotFoundException。

public AsciiArt(String filename, int nrRow, int nrCol){
    this.nrRow = nrRow;
    this.nrCol = nrCol;
    image = new char[nrRow][nrCol];

    try{
        Scanner input = new Scanner(new File(filename));

        int row = 0;
        int column = 0;

        while(input.hasNext()){
            String c = input.next();
            image[row][column] = c.charAt(0);

            column++;

            // handle when to go to next row
        }   

        input.close();
    } catch (FileNotFoundException e) {
        System.out.println("File not found");
        // handle it
    }
}