Reputation: 37
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?
Here is the method that I'm trying to make that will read in the file to the 2D array.
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()){
}
}
}
Upvotes: 0
Views: 1637
Reputation: 1135
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. 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. But this implementation uses Scanner, File, and 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
}
}
Upvotes: 2
Reputation: 1165
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.
Upvotes: 0