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?