2016-10-02 71 views
2
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});,它對同一行的兩個單元格使用相同的行。Java - 需要文件讀取幫助

我需要一些方法來存儲上一行,所以我可以有像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}); 
    }   
} 
+0

好,所以你有當前行,只是簡單地將上一行保存在'String prevLine;'中,你應該很好...... – 3kings

回答

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) { 

} 
+0

非常感謝!我會嘗試一下並用我的更新代碼回覆你。 – Miyazero

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) 
    } 
} 

會是有意義的循環之前,一旦檢索模式?或者getModel()在每次通話中返回不同的模型?