私は、帯域幅のトラフィックを測定するJavaスイングアプリケーションを開発します。 しかし、PCがアプリケーションを保存して終了したときに、合計の送信と受信を のファイルに送信することを願っています。 私のコードでshutdownhookを使用し、自分のPCをシャットダウンするとき ファイルは保存されません! すべてのボディは私を助けることができる? ` 私は、Javaを使用win7_64javaシャットダウンフックが動作しない?
public static void main(String[] args) throws AWTException, IOException, URISyntaxException, Exception {
NewClass n=NewClass.getInstance();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
try {
saveHistory();//save send and recive traffic to file
System.out.println(1);
} catch (IOException ex) {
Logger.getLogger(BandWidthMeter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}, "Shutdown-thread"));
}
}
void saveHistory() throws IOException{
Date date=new Date();
SimpleDateFormat format=new SimpleDateFormat("yyyy/MM/dd hh:mm");
String format1 = format.format(date);
//convert traffic to kiloByte
double session_Send=(double)send/1024;
double session_Recive=(double)recive/1024;
String row=format1+"-"+String.valueOf(session_Send)+"-"+String.valueOf(session_Recive);
try (FileWriter fw = new FileWriter(new File("src/bandwidthmeter/history.txt"),true)) {
fw.append(row);
fw.append("\n");
}
try (//update total.properties
FileOutputStream out = new FileOutputStream("src/bandwidthmeter/total.properties")) {
//convert traffic to megabyte
double sessionSend=(double)send/1048576;
double sessionRecive=(double)recive/1048576;
totalSend+=sessionSend;
totalRecive+=sessionRecive;
prop.setProperty("totalSend",String.valueOf(totalSend));
prop.setProperty("totalRecive",String.valueOf(totalRecive));
prop.store(out,null);
out.close();
}
}
使用しているIDE。どのようにあなたのコードをテストしているか教えてください。 IDEの内部または実行中のサイドIDE? –
あなたのコードはフォーマットが正しくない、デザインが悪い(シングルトン 'NewClass.getInstance()'、 'NewClass'やグリッチのように意思疎通していない悪い名前、' out.close() 'コールが最後に 'try'は冗長ですが、' main() 'では' throws Exception'が 'throws Exception'と重複しています –
@ShineedBasheerなぜですか?IDEと何が関係していますか? – EJP