Share on Google+Share on Google+

Write records into text file from database

In this section, you will learn how to retrieve record from database and store it into text file.

Write records into text file from database

You have already learnt how to insert records from text file to database. But here we are going to retrieve records from database and store the data into the text file. For this purpose, we have created a table in the database. Then using the ResultSet, we have selected the whole table using sql select query and store the data in the ArrayList. This list is then written into the file using for loop.

Here is the code:

import java.sql.*;
import java.util.*;

public class WriteIntoFileFromDatabase {
	public static void main(String[] args) {
		List data = new ArrayList();

		try {
			Connection con = null;
			con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/test", "root", "root");
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery("Select * from employee");

			while ( {
				String id = rs.getString("emp_id");
				String name = rs.getString("emp_name");
				String address = rs.getString("emp_address");
				String contactNo = rs.getString("contactNo");
				data.add(id + " " + name + " " + address + " " + contactNo);

			writeToFile(data, "Employee.txt");
		} catch (Exception e) {

	private static void writeToFile(java.util.List list, String path) {
		BufferedWriter out = null;
		try {
			File file = new File(path);
			out = new BufferedWriter(new FileWriter(file, true));
			for (String s : list) {

		} catch (IOException e) {


Posted on: January 9, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null