Results 1 to 15 of 15
  1. #1
    Plex is offline Member
    Join Date
    Nov 2010
    Posts
    9
    Rep Power
    0

    Default Writing multiple lines to text file at once

    Hey Java experts,

    I'm having a little bit of trouble implementing JDBC into this Java solution.

    The bit of code that I think matters is as follows:

    Java Code:
          while (rs.next()) {
    
            String x = rs.getString ("COLUMN1");
            String s = rs.getString("COLUMN2");
            
            
            String result = (x + "; " + s + "; ");
            
            System.out.println(result);
            
            FileWriter out = new FileWriter("out.txt");
            BufferedWriter writer = new BufferedWriter(out);
            writer.write(result);
            writer.close();
    Basically I'm connecting to a DB via JDBC. After authentication, I'm running a basic SQL query. After the query, I want to print the results depends on how I concatenate the string.

    So far so good.. running the code above will print results in the console.. line-by-line... changing the "result" variable for each line. So I will actually see all, let's say, ~100 lines or so. The problem is when it comes around to writing the variable to the text file, it only prints the very last line that was returned...

    I know this is pretty basic... I could have sworn there was a way to print all of the results at once to the file, or append them one at a time before the variable has a chance to change. I would really prefer this over reading the file after every line and storing it and adding to it.

    Thanks in advance...

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You're creating a new file writer with each iteration of the loop, and each time it's created it overwrites the old one. Better to create one file writer before the while loop.

  3. #3
    Plex is offline Member
    Join Date
    Nov 2010
    Posts
    9
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    You're creating a new file writer with each iteration of the loop, and each time it's created it overwrites the old one. Better to create one file writer before the while loop.
    Aye. Firstly, thanks for your response!

    Secondly, I'm aware that this is the issue. I'm just kind of gray on how to create and write to the file before the loop when it's the loop itself that is providing the results.

    Sorry if I'm not explaining this very well... I'm kind of new to it, as you might be able to gather :D.

    I do appreciate your help!

  4. #4
    Plex is offline Member
    Join Date
    Nov 2010
    Posts
    9
    Rep Power
    0

    Default

    Trying to kind of understand what you meant, I simply moved the line that was just creating the file to before the loop. When executing then, the program writes the first line and then prints this in the console:

    Exception in thread "main" java.io.IOException: Stream closed
    at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)
    at sun.nio.cs.StreamEncoder.write(Unknown Source)
    at java.io.OutputStreamWriter.write(Unknown Source)
    at java.io.BufferedWriter.flushBuffer(Unknown Source)
    at java.io.BufferedWriter.close(Unknown Source)
    at first.Test.main(Test.java:61)


    Thank you again for your assistance :).

  5. #5
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    My guess would be you moved the writer.close() line to before the loop as well. You create the writer before the loop, close it when you're done with it, eg after the loop.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  6. #6
    Plex is offline Member
    Join Date
    Nov 2010
    Posts
    9
    Rep Power
    0

    Default

    Quote Originally Posted by m00nchile View Post
    My guess would be you moved the writer.close() line to before the loop as well. You create the writer before the loop, close it when you're done with it, eg after the loop.
    No sir, the only line I moved on that attempt was:

    FileWriter out = new FileWriter("out.txt");


    Thank you for your response though :).

  7. #7
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Did you move the writer.close() line out of the loop? If you haven't the first iteration of the loop closes the stream, and the second iteration spawns the exception.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  8. #8
    Plex is offline Member
    Join Date
    Nov 2010
    Posts
    9
    Rep Power
    0

    Default

    AH! I see what you mean.

    I moving the writer.close() just outside of the loop (after the closing bracket)-- I was unable to compile at that point because it didn't know what writer was.

    I just not using it at all and just commenting out the close() line, and the program ran; however, nothing was printed at all to the file (but it was created).

    I'm sorry that I'm so noob at this, but your help so far is greatly appreciated.

  9. #9
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Post your updated code snippet again, this way, the guesswork can stop and we'll be able to help you better.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by m00nchile View Post
    Post your updated code snippet again, this way, the guesswork can stop and we'll be able to help you better.
    .... Amen!

  11. #11
    Plex is offline Member
    Join Date
    Nov 2010
    Posts
    9
    Rep Power
    0

    Default

    Quote Originally Posted by m00nchile View Post
    Post your updated code snippet again, this way, the guesswork can stop and we'll be able to help you better.
    Sure. I'll post more of it, too.

    Java Code:
    package first;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.SQLWarning;
    import java.sql.Statement;
    import java.io.*;
    
    public class Test {
    	
    
      public static void main(String[] av) throws IOException{
    	  
    	  
          try {
          Class.forName ("com.ibm.u2.jdbc.UniJDBCDriver");
          Connection conn = DriverManager.getConnection ("(hidden)",
          checkForWarning(conn.getWarnings());
          Statement stmt = conn.createStatement();
          ResultSet rs = stmt.executeQuery("select * from hidden");
    
          int i = 0;
          FileWriter out = new FileWriter("pacer.txt"); 
    
          while (rs.next()) {
    
            String x = rs.getString ("C1");
            String s = rs.getString("C2");
            
            String result = (++i + ": " + x + "; " + s + "; ");
            
            System.out.println(result);
                
            BufferedWriter writer = new BufferedWriter(out);
            writer.write(result);
            writer.close();
    
          }
    
    
          rs.close();
          stmt.close();
          conn.close();
    
          } catch (ClassNotFoundException e) {
          System.out.println("Can't load driver " + e);
          } catch (SQLException e) {
          System.out.println("Database access failed " + e);
          }
          
      }
    
      private static void checkForWarning(SQLWarning warn) throws SQLException  {
    
    
           if (warn != null) {
             System.out.println(" Error \n");
             while (warn != null) {
               System.out.println("SQLState: " +
                 warn.getSQLState());
               System.out.println("Message:  " +
                 warn.getMessage());
               System.out.println("Vendor:   " +
                 warn.getErrorCode());
               System.out.println("");
               warn = warn.getNextWarning();
             }
           }
         }
    }
    I left the close() in there where it was before, because no matter where I tried to move it, I was unsuccessful.

    Thanks again.

  12. #12
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Java Code:
    int i = 0;
          FileWriter out = new FileWriter("pacer.txt"); 
          BufferedWriter writer = new BufferedWriter(out);
          while (rs.next()) {
    
            String x = rs.getString ("C1");
            String s = rs.getString("C2");
            
            String result = (++i + ": " + x + "; " + s + "; ");
            
            System.out.println(result);
                
            //BufferedWriter writer = new BufferedWriter(out); need to move this to before start of loop
            writer.write(result);
            //writer.close(); need to move this outside of loop
    
          }
          writer.close();
    Try this on for size :D
    Ever seen a dog chase its tail? Now that's an infinite loop.

  13. #13
    Plex is offline Member
    Join Date
    Nov 2010
    Posts
    9
    Rep Power
    0

    Default

    Wow..

    You are my god damn hero.

    Thanks so much!! +rep

  14. #14
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    No probs, glad I could help.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  15. #15
    Plex is offline Member
    Join Date
    Nov 2010
    Posts
    9
    Rep Power
    0

    Default

    Now all I need is a way to send the text file that was created to another box via FTP or something and I'm set ;).

Similar Threads

  1. Replies: 4
    Last Post: 11-03-2010, 07:17 PM
  2. Deleting multiple lines of text from a file
    By barman in forum New To Java
    Replies: 4
    Last Post: 06-29-2010, 10:12 AM
  3. Replies: 1
    Last Post: 02-27-2010, 02:29 AM
  4. How to remove 2 last lines in a text file?
    By Marius in forum New To Java
    Replies: 2
    Last Post: 11-30-2008, 04:54 PM
  5. [SOLVED] Writing ArrayList to Text File on seperate Lines
    By shinjitsunohana in forum New To Java
    Replies: 9
    Last Post: 08-27-2008, 06:53 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •