0

I have code written in java that is grabbing the index page of a website, but when I try to save the file it saves a blank document.
Here is the code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.JOptionPane;
import java.io.*;

public class source {

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

    String filename;

    filename = JOptionPane.showInputDialog("Enter the site");
    PrintWriter outputFile = new PrintWriter("files\\"+filename+".html");

    URL url = new URL("http://"+filename);


    URLConnection con = url.openConnection();
    InputStream is =con.getInputStream();

    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    String line = null;


    while ((line = br.readLine()) != null) {
        System.out.println(line);
        outputFile.println(line);
    }
    System.exit(0);
}
}

What am I doing wrong?
Is there anything that I need to add to save html?

4
  • Also, why do you need to call System.exit(0) at the last line of main? Your program will exit anyway. Commented Jul 3, 2013 at 5:24
  • Also, a try catch finally { if (outputfile!=null) outputfile.close() ... } will be fine Commented Jul 3, 2013 at 5:25
  • Or use Java 7 and its try-with-resources syntax. Seriously, who targets Java 6 anymore? Commented Jul 6, 2013 at 1:13
  • follow-up on security.SE: Prevent my site from being copied Commented Jul 8, 2013 at 8:19

3 Answers 3

3

As far as I can see, only two things are missing here.

You failed to close the reader and writer.

Add these at the end.

br.close();
outputFile.close();

PS: It would help us help you, if we know the input as well.

Sign up to request clarification or add additional context in comments.

Comments

1

Do not use System.exit(). It's practically never needed and definitely not here. As paulsm4 said, you're missing the outputFile.close() (br.close() won't matter here), so the writes aren't flushed to disk.

Comments

0

You forgot to close / flush the data.

 BufferedReader br = new BufferedReader(new InputStreamReader(is));

    String line = null;


    while ((line = br.readLine()) != null) {
        System.out.println(line);
        outputFile.println(line);
    }
    br.close();

And your System.exit() causes Jvm to shutdown.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.