简体   繁体   English

读取文件为2D字符数组

[英]Reading a file as a 2d char array

How do you read in data from a text file that contains nothing but char s into a 2d array using only java.io.File , Scanner , and file not found exception? 您如何仅使用java.io.FileScanner和file not found异常从仅包含char的文本文件中读取数据到2d数组中?

Here is the method that I'm trying to make that will read in the file to the 2D array. 这是我试图使该方法将在文件中读取到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()){

        }   
    }
}

Make sure that you're importing java.io.* (or specific classes that you need if that's what you want) to include the FileNotFoundException class. 确保要导入java.io.* (如果需要,则导入所需的特定类)以包括FileNotFoundException类。 It was a bit hard to show how to fill the 2D array since you didn't specify how you want to parse the file exactly. 由于未指定要精确解析文件的方式,因此显示如何填充2D数组有点困难。 But this implementation uses Scanner, File, and FileNotFoundException. 但是此实现使用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
    }
}

A rough way of doing it would be: 大致的方法是:

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

However im sure there are other ways which would be much better and more efficient but you get the principle. 但是我确信还有其他方法会更好,更有效,但是您会明白这一原理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM