I have created a table viewer and displaying the contents in the table.Now i have created a button called save which has to save all the contents of the table into a file .I have created a dialog window to give the file name but i am not getting how to save the complete data in the table to a text file.So how can we save the complete data in the table to text file .The code for dialogbox is as follows
Button btnSave= new Button(topComposite, SWT.BUTTON2);
btnSave.setText("Save");
//btnSave.addSelectionListener(new OpenFiler());
btnSave.addSelectionListener(new SelectionAdapter() {
@Override public void widgetSelected(final SelectionEvent e){
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
dialog.setText("Save");
String[] filterExt = { "*.log" };
dialog.setFilterNames(filterExt);
String absolutePath = dialog.open();
if (absolutePath == null)
return;
dialog.setFilterExtensions(new String[] { "*.log" }); dialog.setFilterPath("c:\\"); // Windows path
}
});
Please help me how can we save the complete data in the table to a text file.
Use this code. viewer
is the instance of your table viewer. Add this code at the end of the addSelectionListener
method of button btnSave
.
TableItem[] items = viewer.getTable().getItems();
File fl = new File(dialog.getFilterPath() + File.separator + dialog.getFileName());
FileWriter flwr;
int cls = viewer.getTable().getColumnCount();
try {
flwr = new FileWriter(fl);
for (int i = 0; i < items.length; i++) {
for (int j = 0; j <= cls; j++) {
flwr.write(items[i].getText(j) + "\t");
}
flwr.write("\n");
}
flwr.flush();
flwr.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}