[英]Java - Help needed with file reading
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
的文件中读取的。 我想要的是为文本文件的每2行在表上创建1行,但是正如您所看到的,我正在使用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});
}
}
每次循环读两行怎么样?
String line1, line2;
while ((line1 = reader.readLine()) != null && (line2 = reader.readLine()) != null) {
//model.addRow(new Object[]{line1, line2});
}
// for odd line
if (line1 != null) {
}
应该这样做:
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()
在每次调用时返回不同的模型?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.