将文件作为二维字符数组读取 [英] Reading a file as a 2d char array

查看:49
本文介绍了将文件作为二维字符数组读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我尝试创建的方法,它将文件读入到2D数组中。

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.io.*(或您需要的特定类,如果这是您想要的)以包括FileNotFoundException类。演示如何填充2D数组有点困难,因为您没有指定希望如何准确解析文件。但此实现使用了扫描仪、文件和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
    }
}

这篇关于将文件作为二维字符数组读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆