本文介紹了將文件作為二維字符數(shù)組讀取的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
如何僅使用java.io.File
、Scanner
和文件未找到異常將數(shù)據(jù)從只包含char
的文本文件讀入到二維數(shù)組中?
這是我嘗試創(chuàng)建的方法,它將文件讀入到2D數(shù)組中。
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()){
}
}
}
推薦答案
確保您正在導(dǎo)入java.io.*
(或您需要的特定類,如果這是您想要的)以包括FileNotFoundException
類。演示如何填充2D數(shù)組有點困難,因為您沒有指定希望如何準(zhǔn)確解析文件。但此實現(xiàn)使用了掃描儀、文件和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
}
}
這篇關(guān)于將文件作為二維字符數(shù)組讀取的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,