you can do it like down below. I've heard that not many people use the .split() String method, but I love using it haha. you're gonna have to import java.io.File
, java.io.FileNotFoundException
, and java.util.Scanner
. Also, this is assuming that the text file uses tabs as its delimeter. If the text file is a different dimension, just change ROWS
and COLS
to the new dimensions of the new array
final int ROWS = 5;
final int COLS = 5;
int[][] nums = new int[ROWS][COLS];
// this is used only in java 7 (not java 6)
try (Scanner input = new Scanner(new File("filename.txt"))) {
int row = -1; // since we're incrementing row at the start of the loop
while(input.hasNext()) {
row++;
String[] line = input.nextLine().split("\t");
for(int col = 0; col < COLS; col++) {
try {
nums[row][col] = Integer.parseInt(line[col]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
} catch (FileNotFoundException e) {
// do something here
e.printStackTrace();
}
If you are using Java 6, then the outer try/catch just looks like:
try {
Scanner input = new Scanner(new File("filename.txt"));
// insert rest of code here
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}