1

I am trying to get data from URL and write it to a file, and I got the data from the URL but the file is empty, and below my code:

public class LiveRead {
    public static void main(String[] args){
        try {
            URL u = new URL("http://quotes.rest/qod.json?category=life");
            HttpURLConnection hr = (HttpURLConnection) u.openConnection();
            if (hr.getResponseCode() == 200){
                InputStream im = hr.getInputStream();
                StringBuffer sb = new StringBuffer();
                BufferedReader br = new BufferedReader(new InputStreamReader(im));
                FileOutputStream fo = new FileOutputStream("/Users/macos/Desktop/json");
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fo));
                String line = br.readLine();
                while (line != null){
                    System.out.println(line);
                    bw.write(line);
                    bw.newLine();
                    line = br.readLine();
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

and when I open /Users/macos/Desktop/json, that file is empty. What's wrong and how to resolve it?

daedsidog
  • 1,732
  • 2
  • 17
  • 36
Fzee
  • 33
  • 6

1 Answers1

2

You should explicitly flush and close your writer, and not assume Java will do it for you when the program terminates:

bw.flush();
bw.close();
Mureinik
  • 297,002
  • 52
  • 306
  • 350