[英]Reading 2d array from file using BufferedReader in java
我正在尝试加载文件,如下所示:
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
到sudokuboard类中的2d数组。
我为此使用的功能如下:
@Override
public SudokuBoard read() throws DaoException {
SudokuBoard board = new SudokuBoard();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
while (in.ready() == true) {
for (int row = 0; row < 9; row++) {
for (int column = 0; column < 9; column++) {
board.setDigit(row, column, in.read());
//System.out.print(in.read() + ", ");
}
in.read(); // this is important
System.out.println("");
}
}
} catch (IOException e) {
throw new DaoException(DaoException.IO_EXCEPTION, e);
}
return board;
}
阅读此文件后,我得到的是:
0 0 0 6 115 113 0 126 0
0 0 0 4 115 113 0 126 0
0 0 0 2 115 113 0 126 0
0 0 0 3 115 113 0 126 0
0 0 0 8 115 113 0 126 0
0 0 0 5 115 113 0 126 0
0 0 0 1 115 113 0 126 0
0 0 0 9 120 120 -1 -1 -1
-1 -1 -1 -1 -1 -1 -1 -1 -1
有人知道问题出在哪里吗?
感谢帮助 !
我一直在玩你的代码。 这就是我想出的。 当然,有更好的解决方案,但是我认为这一解决方案将为您服务。
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream("C:/Users/Rod/Desktop/123.txt")));
int column = 0;
int row = 0;
int pom;
while ((pom = in.read()) != -1) {
pom -= 48;
if (pom > -1 && pom < 10) {
System.out.print("" + pom + ", ");
// board.setDigit(row, column, pom);
column++;
if (column > 8) {
column = 0;
System.out.println("");
row++;
if (row > 8)
break;
}
}
}
} catch (Exception e) {
System.out.print("ERROR");
// e.printStackTrace();
} finally {
if (in != null)
in.close();
}
告诉我,对您来说效果很好。
附注:我在注释后编辑了代码。 祝一切顺利。
您如何看待该解决方案?
public static int[][] readBoard(String boardFileName) throws IOException {
int[][] board = new int[9][9];
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(boardFileName));
for(int i = 0; i < 9 && reader.ready(); i++) {
String[] splittedRow = reader.readLine().split(" "); // split using the space character
for(int j = 0; j < 9; j++) {
board[i][j] = Integer.parseInt(splittedRow[j]);
}
}
return board;
} catch(IOException e) {
throw e; // lets the caller manage the exception
} finally {
assert reader != null;
reader.close();
}
}
显然,不要在意完全不存在的错误管理:)
我希望这段代码对您有帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.