我寫了一個java代碼打印我的輸出在位於文檔,但執行的代碼文件後,文件仍然是empty.Can有人讓我犯錯誤正在使用NetBeans創建此程序如何使用java獲取輸出到文件?
代碼
import java.net.HttpURLConnection;
import java.net.URL;
import java.lang.*;
import java.io.*;
public class NewClass1 {
static long start = 0;
static long finish = 0;
static long time;
public static void main(String[] args) throws Exception {
BufferedWriter bw = null;
FileWriter fw = null;
for (int i = 0; i <= 5; i++) {
String stack_url = "https://www.google.lk/";
try {
URL url = new URL(stack_url);
HttpURLConnection httpUrlConnect = (HttpURLConnection) url.openConnection();
httpUrlConnect.setConnectTimeout(10);
start = System.currentTimeMillis();
httpUrlConnect.connect();
if (httpUrlConnect.getResponseCode() == 200) {
finish = System.currentTimeMillis();
System.out.println(stack_url + " - " + httpUrlConnect.getResponseMessage() + " took " + (finish - start) + " Milli Seconds.");
}
if (httpUrlConnect.getResponseCode() == httpUrlConnect.HTTP_NOT_FOUND) {
System.out.println(stack_url + " - " + httpUrlConnect.getResponseMessage() + " - " + httpUrlConnect.HTTP_NOT_FOUND);
}
} catch (Exception e) {
}
time = finish - start;
finish = System.currentTimeMillis();
System.out.println("Total Time for page load - " + (finish - start));
try {
Integer _time = (int) (long) time;
String content = Integer.toString(_time);
fw = new FileWriter("time.sql");
bw = new BufferedWriter(fw);
bw.write(content);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
if (fw != null) {
fw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Thread.sleep(1000);
}
}
** **從不} write'趕上(例外五){ }'。始終處理異常。 atleast logg stacktrace – Jens
我想你會得到一個異常。通過閱讀一個URL。在這種情況下,將創建一個空文件 – Jens
此外,你創建一個循環中的文件,所以在每次執行該文件將被覆蓋 – Jens