Search code examples
javajsondownloadwunderground

Downloading web-source Java


import java.io.*;
import java.util.*;
import java.net.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class URLReader {

     public static void main(String[] args) {
         download();
     }

     public static void download() {
         try {
             URL oracle = new URL("http://api.wunderground.com/api/54f05b23fd8fd4b0/geolookup/conditions/forecast/q/US/CO/Denver.json");
             BufferedReader in = new BufferedReader(
             new InputStreamReader(oracle.openStream()));

             File file = new File("C:\\Users\\User\\Desktop\\test2.json");
             if (!file.exists()) {
                 file.createNewFile();
             }
             FileWriter fw = new FileWriter(file.getAbsoluteFile());
         BufferedWriter bw = new BufferedWriter(fw);

             String inputLine;
             while ((inputLine = in.readLine()) != null) {
                 bw.write(inputLine+"\n");
             }
             in.close();
             System.out.println("Finished with no errors...");
         }
         catch(MalformedURLException e){System.out.println("err1");}
         catch(IOException e){System.out.println("err2");}
     }
}

I'm trying to downloading this JSON file onto my computer, but however it stops short. It ends after the 8192th character and goes no longer. Otherwise it works fine, any ideas on what I'm doing wrong?

Also is this the correct way to download a webpages source, can someone give me some better techniques on that to help me along?


Solution

  • You're forgetting to close the BufferedWriter :-)

    in.close();
    bw.close(); // Add this here
    System.out.println("Finished with no errors...");
    

    So the Writter can commit the rest of the data stream to the file