Share on Google+Share on Google+

Insert text file data into Database

In this section, you will learn how to insert the text file data into the database using Java Programming.

Insert text file data into Database

In this section, you will learn how to insert the text file data into the database. For this purpose, we have created a 'student.txt' file consisting of students information i.e, id, name, course and department. Now to read this file, we have used DataInputStream and transfer the data to the ArrayList. This list is then iterated through the Iterator interface. After that we have used split() method to break the string data. This data is then inserted into the database.

Here is the student.txt:

1       A       MCA      ComputerScience
2       B       Btech       Mechanical
3       C       Btech       Electrical
4       D       MBA       Management
5       E        LLB        Law
6       F        MBBS    MedicalScience

Here is the code of

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

public class InsertFileData{
public static void main(String[]args){
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/register""root""root");
 Statement st=con.createStatement();

FileInputStream fstream = new FileInputStream("C:\\Answers\\Swing\\student.txt");
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    ArrayList list=new ArrayList();
    while ((strLine = br.readLine()) != null){
  Iterator itr;
    for (itr=list.iterator(); itr.hasNext()){
    String [] splitSt =str.split(" ");
    String id="",name="",course="",deptt="";
      for (int i = ; i < splitSt.length ; i++) {

int k=st.executeUpdate("insert into student(id,name,course,department) values
catch(Exception e){}


Posted on: October 24, 2009 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