Java - 文件读取所需的帮助

时间:2016-10-02 03:43:36

标签: java file

public void readFile() throws IOException
{
    try (BufferedReader reader = new BufferedReader(new FileReader("Data.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
        DefaultTableModel model = (DefaultTableModel) pracListTeacherTable.getModel();
        model.addRow(new Object[]{line, line});

}
嘿大家好我有这段代码基本上从一个名为Data.txt的文件中读取。我想要的是文本文件的每两行在表格上创建一行,但是你可以看到我正在使用model.addRow(new Object[]{line, line});,它对同一行的两个单元格使用相同的行。

我需要一些方法来存储前一行,所以我可以使用model.addRow(new Object[]{line, nextline});这样的东西但是我无法弄清楚如何做到这一点!

如果有人能帮助我,那就太棒了。

更新:感谢shaoyihe的工作!

public void readFile() throws IOException {
    try (BufferedReader reader = new BufferedReader(new FileReader("Data.txt"))) {
    String line1, line2;
    while ((line1 = reader.readLine()) != null && (line2 = reader.readLine()) != null) {
        DefaultTableModel model = (DefaultTableModel) pracListTeacherTable.getModel();
        model.addRow(new Object[]{line1,line2});
    }        
}

2 个答案:

答案 0 :(得分:0)

如何在每个循环中读取两行?

String line1, line2;
while ((line1 = reader.readLine()) != null && (line2 = reader.readLine()) != null) {
//model.addRow(new Object[]{line1, line2});
}

// for odd line
if (line1 != null) {

}

答案 1 :(得分:0)

这应该这样做:

      var xRedIndex = Math.floor((e.offsetX - 3 / 4 * boxWidth) / (boxWidth / 2));
      var yRedIndex = Math.floor((e.offsetY - 3 / 4 * boxHeight) / (boxHeight / 2));
      if (xRedIndex % 2 === 0 && yRedIndex % 2 === 0) {
        console.log("red");
        console.log("Red grid x: " + (xRedIndex / 2));
        console.log("Red grid y: " + (yRedIndex / 2));
      } else {
        console.log("gray");
        var gridPosX = Math.floor(e.offsetX / boxWidth);
        var gridPosY = Math.floor(e.offsetY / boxHeight);
        grid[gridPosX][gridPosY] = 0;
      }

在循环之前检索模型一次是否有意义?或public void readFile() throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader("Data.txt"))) { String line; String [] lines = new String[2]; int nextLine = 0; while ((line = reader.readLine()) != null) { System.out.println(line); lines[nextLine++] = line; // check if we're at the second line if (nextLine == 2) { DefaultTableModel model = (DefaultTableModel) pracListTeacherTable.getModel(); model.addRow(lines); nextLine = 0; } } if (nextLine == 1) { // odd number of lines in file (error?) // lines[0] contains the odd (last) line // lines[1] contains the previous line (last of the previous pair) } } 每次通话都会返回不同的模型吗?