[英]Receiving message and saving it into a file in current directory
這是關於以下問題:接收消息並將其保存到當前目錄中的文件中。 我的問題是,即使收到了消息,我也無法將其寫入文件。 文件已更新,但為空。 消息仍然打印在界面上。 我想要的是消息在文件內,而不是打印在界面上。
這是代碼
public void receiveMessages() {
File file = new File ("msgs.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(file);
SealedObject encrypedSealedObject = null;
while(true){
try {
String message = this.crypto.decryptMsg(encrypedSealedObject);
printWriter.println(message);
}
catch (IOException e) {
break;
}
}
}
//catching exceptions ``here.... etc
}
謝謝您的幫助!
可刷新是可刷新數據的目標。 調用flush方法將任何緩沖的輸出寫入基礎流。
因此,您必須將輸出刷新到文件。 因此,您必須使用pw.flush()。
上面的代碼將重寫文件,並且不會追加后續消息。 如果這是您的要求,那就可以了。 但是,我建議以下幾點:
PrintWriter pw = null; if (appendToFile) { pw = new PrintWriter(new FileWriter(filename, true)); } else { pw = new PrintWriter(new FileWriter(filename)); }
不需要使用2 try and catch,因為在這兩個語句中都拋出了IOException。 而且我建議拋出Throwable並在頂層處理錯誤,這是一個好習慣,而且維護起來也更容易。 函數調用只能執行邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.