Solved

Reading a file and collecting data using java

Posted on 2013-05-10
9
628 Views
Last Modified: 2013-06-06
From the given sql file, how can i read and store all the insert statements in an ArrayList<String> using java code? Any help with code snippet is much appreciated with points.
temp.sql
0
Comment
Question by:Sreejith22
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +1
9 Comments
 
LVL 16

Expert Comment

by:krakatoa
ID: 39155176
You mean trawling a textfile for such keywords?
0
 
LVL 16

Expert Comment

by:Valeri
ID: 39155189
read the file line by line. If the line startsWith "INSERT INTO" concatenate the next lines until you reach the line that endsWith ";"
0
 

Author Comment

by:Sreejith22
ID: 39155192
start should be "INSERT INTO" and end should be ");"  .  When it first hits ");" , after an "INSERT INTO" that entire start to end should be an entry of array list.

Basically, I need to get all the insert into sql statements contained in this attached "temp.sql" file
0
Congratulations! You’re Certified – Now What?

Starting a new career can be overwhelming. Becoming certified in your field of expertise is a great start, but where do you go from here?  Here are some tips to help you on your career journey.

 

Author Comment

by:Sreejith22
ID: 39155194
i would appreciate any correct code snippets
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39155280
Why would you need to separate the INSERT statements from the rest of the ddl file?
0
 
LVL 16

Expert Comment

by:Valeri
ID: 39155281
Here is the code. After the test you can remove the lines that contain "System.out.println".
==========================================================================

import java.io.FileInputStream;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.List;
import java.util.ArrayList;

public class ReadInserts {

    private static List<String> insertsInto = new ArrayList<String>();

    public static void main(String[] args) {
        try {
            // Open the file
            FileInputStream fstream = new FileInputStream("c:\\yourFolder\\temp.sql");
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
           
            String strLine; boolean concatenate = false; String statement = "";
            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {
                // print the content on the console
                System.out.println(strLine);

                if (strLine.startsWith("INSERT INTO")) {
                    concatenate = true;
                }

                if (concatenate) statement += (strLine + "\n");

                if (strLine.endsWith(";")) {
                    concatenate = false;
                    if (statement.length() > 0) System.out.println(">>> : " + statement);
                    if (statement.length() > 0) insertsInto.add(statement);
                    statement = "";
                }
            }
            //Close the input stream
            in.close();
        } catch (Exception e){//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39155354
DataInputStream in = new DataInputStream(fstream);

Open in new window


DataInputStream is unnecessarily specialized for reading text. All you need is
BufferedReader br = new BufferedReader(new FileReader("temp.sql")); // (without the literal)

Open in new window

if (concatenate) statement += (strLine + "\n");

Open in new window

String concatenation should be avoided. Use StringBuilder instead
0
 
LVL 16

Accepted Solution

by:
Valeri earned 500 total points
ID: 39160598
Yes, CEHJ is right. DataInputStream is not needed in this case. please change the code in this way:
==================================================================
import java.io.*;
import java.util.List;
import java.util.ArrayList;

public class ReadInserts {

    private static List<String> insertsInto = new ArrayList<String>();

    public static void main(String[] args) {
        try {
            // Open the file
            FileReader fileReader = new FileReader("c:\\yourFolder\\temp.sql");
            BufferedReader buffReader = new BufferedReader(fileReader);

            String strLine; boolean concatenate = false; String statement = "";
            //Read File Line By Line
            while ((strLine = buffReader.readLine()) != null)   {
                // print the content on the console
                System.out.println(strLine);

                if (strLine.startsWith("INSERT INTO")) {
                    concatenate = true;
                }

                if (concatenate) statement += (strLine + "\n");

                if (strLine.endsWith(";")) {
                    concatenate = false;
                    if (statement.length() > 0) System.out.println(">>> : " + statement);
                    if (statement.length() > 0) insertsInto.add(statement);
                    statement = "";
                }
            }
            buffReader.close();
        } catch (Exception e){//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
}

=======================================
String concatenation is not harmful in this case.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39160722
A potentially more serious problem is when the lines do not begin with 'INSERT INTO' or end with ';' (they've no need to)
0

Featured Post

Stressed Out?

Watch some penguins on the livecam!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question