How To Get And Set Jtable Data To Txt File Using Java NetBeans
In this Java Tutorial we will see How To Import Text From Text File And Set It Into JTable Rows & Export JTable Rows Data To A Txt File Using FileWriter + BufferedWriter + FileReader In Java NetBeans .
Project Source Code:
// button to export data to text file
private void jButtonExportActionPerformed(java.awt.event.ActionEvent evt) {
String filePath = "C:\\Users\\omar\\Desktop\\myfolder\\txtfile.txt";
File file = new File(filePath);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < jTableExport.getRowCount(); i++){//rows
for(int j = 0; j < jTableExport.getColumnCount(); j++){//columns
bw.write(jTableExport.getValueAt(i, j).toString()+" ");
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(JTable_import_and_export_to_text_file.class.getName()).log(Level.SEVERE, null, ex);
}
}
// button to import data from text file
private void jButtonImportActionPerformed(java.awt.event.ActionEvent evt) {
String filePath = "C:\\Users\\omar\\Desktop\\myfolder\\txtfile.txt";
File file = new File(filePath);
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
DefaultTableModel model = (DefaultTableModel)jTableImport.getModel();
Object[] lines = br.lines().toArray();
for(int i = 0; i < lines.length; i++){
String[] row = lines[i].toString().split(" ");
model.addRow(row);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(JTable_import_and_export_to_text_file.class.getName()).log(Level.SEVERE, null, ex);
}
}
OutPut:
Download Projects Source Code
4 comments
commentslone:
ReplyObject[] lines = br.lines().toArray();
lines()//Do not exists
Need help as i get an error with Export
ReplyHello sir, I get error with export file. I will appreciate if you reply me.Thank you
ReplyHi, why the error says that cannot find symbol of jTableImport?
Reply