I am new to java and I need to create a program that reads text from a txt file and puts it into a jtable, the format in the txt file will be like "b3:42". And I need to read those and put b3 in the first column of the table and 42 in the next column. Could you help me ? And sorry for my english.
you can refer below code .
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.*;
public class HelloWorld{
private static final String FILENAME = "input.txt";
public static void main(String []args){
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String s;
String[][] data = new String[2][2];
br = new BufferedReader(new FileReader(FILENAME));
int i = 0;
while ((s = br.readLine()) != null) {
data[i]= s.split(":");
i++;
}
String column[]={"COL1","COL2"};
JTable jt=new JTable(data,column);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Some suggestions
You can read txt file line by line using BufferedReader and related chained stream in this way:
public class TestSO {
public static void main(String[] args) {
String line = "";
try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("yourfile.txt")))){
while ((line = br.readLine()) != null) {
// Process the line
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In order to split your line into pieces you need you must use line.split(":") You get 2 tokens, the one before the colon and the one after it.
String tokens[] = line.split(":");
According to JTable documentation you can create a JTable as JTable(Object[][] rowData, Object[] columnNames)
So you can use tokens you read and parsed above to create the rowData array.
Then create the array for the column names:
//headers for the table
String[] columns = new String[] {
"Col1", "Col2"
};
At the end just creare the JTable passing it the arrays with data and column names:
//create table with data
JTable table = new JTable(rowData, columnNames);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.