【问题标题】:Reading a file as a 2d char array将文件读取为二维字符数组
【发布时间】:2017-02-08 00:23:39
【问题描述】:

如何仅使用 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()){

        }   
    }
}

【问题讨论】:

    标签: java arrays 2d java.util.scanner


    【解决方案1】:

    确保您正在导入 java.io.*(或您需要的特定类)以包含 FileNotFoundException 类。展示如何填充 2D 数组有点困难,因为您没有指定要如何准确解析文件。但是这个实现使用了 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
        }
    }
    

    【讨论】:

    • 谢谢你,这有助于唤起我的记忆。我一直在倾注不同的代码,有时我忘记了。
    • 你不增加row吗?总是 0 吗?
    • 您增加注释“// 处理何时转到下一行”所在的行。我没有显示行被递增,因为 OP 没有指定行的大小或它们如何检测行尾。但解决方案是:如果所有行的长度相同(即所有 7 列宽),则每 7 列递增该行。如果行的长度不同(具有可变列),那么您将检查您是否在行尾
    【解决方案2】:

    一个粗略的方法是:

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

    但是我确信还有其他方法会更好,更有效,但你明白了这个原则。

    【讨论】:

      猜你喜欢
      • 2012-05-30
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      • 2015-05-17
      • 1970-01-01
      相关资源
      最近更新 更多