「MyLogger.java」
Java
1public final class MyLogger { 2 private static MyLogger theInstance; /* 唯一のインスタンス保存用 */ 3 private FileWriter writer; 4 private MyLogger() { 5 try{ 6 this.writer = new FileWriter("C:\Users\hoge\Desktop\testlog.txt"); 7 }catch(IOException e) { /* エラー処理は省略 */ } 8 } 9 public void log(String msg) throws IOException { 10 this.writer.write(msg); 11 } 12 public static MyLogger getInstance() { 13 if(theInstance == null) theInstance = new MyLogger(); 14 return theInstance; 15 } 16}
「Main.java」
Java
1public class Main { 2 public static void main(String[] args) throws IOException { 3 4 MyLogger myLogger1 = MyLogger.getInstance(); 5 myLogger1.log("first"); 6 7 MyLogger myLogger2 = MyLogger.getInstance(); 8 myLogger2.log("second"); 9 10 } 11}
スッキリわかるJava入門実践編第2版で上記の通りにしても、ログが出力されません。
this.writer.write(msg);の後にthis.writer.close()とすれば、firstだけ出力されるのですが、secondも出力する方法はありますでしょうか。
※C:\Users\hoge\Desktop\testlog.txtにはすでにある状態です。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/25 01:24