View Single Post
Old 02-18-2006, 05:36 PM   PM User | #1
YodaCows
New to the CF scene

 
Join Date: Jan 2006
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
YodaCows is an unknown quantity at this point
Exclamation Java - Output to file

This is an assignment, so I'm just looking for a hint.
Hopefully someone can help, it seems like it should be easy.

This is the original code:

Code:
import java.io.*;
import java.net.*;

public class scrapeSite
{
   public static void main( String[] args )
   {
      try
      {
         String line;
         BufferedReader br;
         BufferedWriter bw;

         // create a connection to 'www.yahoo.com' on port 80
         Socket s = new Socket( "www.yahoo.com", 80 );

         // create the reader and writer objects
         br = new BufferedReader( new InputStreamReader( s.getInputStream() ));
         bw = new BufferedWriter( new OutputStreamWriter( s.getOutputStream() ));

         // request the 'root' page
         bw.write( "GET / HTTP/1.0\n\n" );
         bw.flush();

         // while more lines, output to the standard output stream
         while( (line = br.readLine()) != null )
         {
            System.out.println( line );
         }
      }
      catch( IOException e )  // catch any errors
      {
         System.out.println( "There was an IOException error!" );
      }
   }
}
My assignment is to simply output the result to a text file. After looking through some books and other tutorials, I've come up with this

Code:
import java.io.*;
import java.net.*;

public class scrapeSite
{
    public static FileOutputStream Output;
    public static PrintStream file;
    public static String line;

   public static void main( String[] args )
   {
      try
      {
         BufferedReader br;
         BufferedWriter bw;

         // create a connection to 'www.yahoo.com' on port 80
         Socket s = new Socket( "www.yahoo.com", 80 );

         // create the reader and writer objects
         br = new BufferedReader( new InputStreamReader( s.getInputStream() ));
         bw = new BufferedWriter( new OutputStreamWriter( s.getOutputStream() ));

         // request the 'root' page
         bw.write( "GET / HTTP/1.0\n\n" );
         bw.flush();

         // while more lines, output to the standard output stream
         while( (line = br.readLine()) != null )
         {
            //System.out.println( line );            
            Output = new FileOutputStream("myfile.txt");
            // Connect print stream to the output stream
            file = new PrintStream(Output);
            file.println (line);
         }
      }
      catch( IOException e )  // catch any errors
      {
         System.out.println( "There was an IOException error!" );
      }
   }
}
It almost works, except only the last line gets writtent to the txt file.
Am I on the right track?

Thanks

~YC
YodaCows is offline   Reply With Quote