java 实现将txt文件逐行提取到jtable 表格中代码实现
时间: 2024-03-22 20:42:37 浏览: 56
以下是Java代码实现将txt文件逐行提取到JTable表格中的示例:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TxtToJTableExample extends JFrame {
private JTable table;
private DefaultTableModel model;
public TxtToJTableExample() {
setTitle("TxtToJTable Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
// Create a table with 2 columns
String[] columnNames = {"Column 1", "Column 2"};
model = new DefaultTableModel(columnNames, 0);
table = new JTable(model);
// Add the table to a scroll pane
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
// Read the lines from the txt file and add them to the table
ArrayList<String[]> lines = new ArrayList<String[]>();
try {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
lines.add(parts);
}
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
for (String[] parts : lines) {
model.addRow(parts);
}
}
public static void main(String[] args) {
TxtToJTableExample example = new TxtToJTableExample();
example.setVisible(true);
}
}
```
在上面的代码中,我们首先创建了一个具有两列的JTable。然后,我们使用BufferedReader从txt文件中逐行读取数据,并将每一行的数据分割成字符串数组。最后,我们将每一行的字符串数组添加到JTable中的DefaultTableModel对象中,从而将数据显示在JTable中。
阅读全文