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:
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
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