我正在尝试从URL获取数据并将其写入文件,并且从URL获得数据,但是文件为空,并且位于我的代码下方:
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);
}
}
}
当我打开/Users/macos/Desktop/json
时,该文件为空。怎么了?如何解决?
答案 0 :(得分:2)
您应该明确地{@ {1}}和flush
您的编写者,并且不要假设程序终止时Java会为您完成:
close