简体   繁体   中英

Write Java Vector To Delimited File

I am connecting to an Oracle database and querying multiple tables. My current code creates the connection and calls a PL/SQL function which contains the query. Once I have the result set, I add it to a Vector (as I am unsure the number of records each query will result in).

My problem is that I am unsure how to write a delimited file from the Vector. I imagine once I have added my result set to it, it is simply one gigantic string. I need to be able to receive each field from the query and delimit between them, as well as keep rows separate.

Here is my code:

 public static void main(String[] args) throws SQLException {

    // instantiate db connection
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
    }catch (Exception e) {
        throw new SQLException("Oracle JDBC is not available", e);
    }

    // define connection string and parameters
    String url = "jdbc:oracle:thin:@//host:port/sid";
    Connection conn = DriverManager.getConnection(url, "USERNAME","PASSWORD");


    CallableStatement stmt = conn.prepareCall("{? = CALL <functionname>(?)}");

    // get result set and add to a Vector
    ResultSet rs = stmt.executeQuery();
    Vector<String> results = new Vector();
    while ( rs.next() ){
        results.add(rs.getString(1));
    }

    // close result set, sql statement, and connection
    rs.close();
    stmt.close();
    conn.close();

    // write Vector to output file,
    // where the file name format is MMddyyyy.txt
    try {

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
    String dateStr = sdf.format(cal.getTime());

    FileWriter fwrite = new FileWriter(dateStr + ".txt");
    BufferedWriter out = new BufferedWriter(fwrite);

    for(int i = 0; i < results.size(); i++)
    {
        String temp = results.elementAt(i);
        out.write(temp);
    }

    out.close();

}catch (Exception e) {
    System.err.println("Error: " + e.getMessage());
}
}

I am just unsure how to go about getting the information from the db and writing it to a delimited file. Thanks in advance!

If you are unsure about the number of fields in each of your rows , then probably, it won't be possible. Because to fetch all the field values from database, you need to know what is the type of each fields, and the number of fields.

But, I'll post an example for when you have fixed number of fields, that you know.

Suppose you have 4 columns per row. Now to display it in tabular form, you would have to use List of List .

If you are using Vector , use Vector of List .

Here's an example for List of List : -

List<List<String>> results = new ArrayList<List<String>>();

while ( rs.next() ) {
    List<String> tempList = new ArrayList<String>();
    tempList.add(rs.getString(1));
    tempList.add(rs.getString(2));
    tempList.add(rs.getString(3));
    tempList.add(rs.getString(4));

    results.add(tempList);
}

Then to print it, use this loop: -

for (List<String> innerList: results) {
    for (String fields: innerList) {
        System.out.print(fields + "\t");
    }
    System.out.println();
}

You can write it in the same form to your BufferedWriter .

Use results.toString() and truncate the braces( [] ) from resulting string to write all values as comma separated at once in the file.

    //toString() returns comma separated string values enclosed in []
    String resultString = results.toString();

    //truncate leading '[' and termincating ']'
    resultString = resultString.substring(1, resultString.length()-1);

    //if comma is not your delimiter then use String.replaceAll() 
    //to replace `,` with your delimiter

    //write comma separated elements all at once
    out.write(resultString);

So here if you have added str1 , str2 in the results Vector, then resultString with have value as str1, str2 , which you may write at once using your BufferedWriter out .

Also please use Generics in both the sides of initialization as:

     Vector<String> results = new Vector<String>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM