Skip to main content

java i/o (how to write data to file .txt or .dat, etc line by line )

1 reply [Last post]
anindita
Offline
Joined: 2010-08-25
Points: 0

I want to ask about how to write data to file .txt or .dat, etc line by line

please give me the source code

thank's before

Message was edited by: anindita

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
boafo
Offline
Joined: 2010-08-30
Points: 0

/**There are a variety of ways to get this done.
*Your approach will depend largely on your data source
*Let's approach it from this angle.let's get data from a jtable instance and write *each row of the table data per line in our destination file
*/

//File may be one selected by user by means of a filechooser
File file = ........
JTable table = ........

if(table != null && file != null)
{
PrintWriter writer = null;
try
{
TableModel model = table.getModel();
writer = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
for(int i = 0; i < model.getRowCount(); ++i)
{
for(int j = 0; model.getColumnCount(); ++j)
{
//write each row of table data per line in destination file
writer.print(model.getValueAt(i,j).toString + " ");
}
//Move insertion point to next line in destination file
writer.println("");
}
}
catch(IOException ioe)
{
//Handle exception here
}
finally
{
if(writer != null)
writer.close();
}

}