Solved

Reading a file and collecting data using java

Posted on 2013-05-10
9
610 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
  • 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
 

Author Comment

by:Sreejith22
ID: 39155194
i would appreciate any correct code snippets
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Checkbox and ListView in Android Layout 4 56
mockito example issue 8 62
simple java question 3 44
xampp tool 12 24
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
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 about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

911 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now