2016-04-06 85 views
2

我寫了一個程序,允許用戶在一個文件中存儲多個備忘錄。我想出瞭如何在Java中使用PrintWriter &文件,但是我的問題與我的輸出有關。當我在記事本中檢查文件時,我只能輸入一個備忘錄,沒有問題&,只有一個備忘錄存在。下面的代碼:PrintWriter&File in java

import java.util.*; 
import java.io.*; 

public class MemoPadCreator{ 

    public static void main(String[] args) throws FileNotFoundException { 

    Scanner input = new Scanner(System.in); 
    boolean lab25 = false; 
    File file = new File("revisedLab25.txt"); 
    PrintWriter pw = new PrintWriter (file); 
    String answer = ""; 

    do{ 
     while(!lab25){ 

     System.out.print("Enter the topic: "); 
     String topic = input.nextLine(); 

     Date date = new Date(); 
     String todayDate = date.toString(); 

     System.out.print("Message: "); 
     String memo = input.nextLine(); 

     pw.println(todayDate + "\n" + topic + "\n" + memo); 
     pw.close(); 

     System.out.print("Do you want to continue(Y/N)?: "); 
     answer = input.next(); 
     } 

    }while(answer.equals("Y") || answer.equals("y")); 

    if(answer.equals("N") || answer.equals("n")){ 
     System.exit(0); 
    } 

    } 
} 

下面是輸出:

Enter the topic: I love food! 
Message: Food is life! 
Do you want to continue(Y/N)?: Y 
Enter the topic: Message: 

如何去改變它,以便輸出可以讓我繼續儲存的備忘錄,直到我告訴它停下來?

+0

什麼是確切的問題?程序的兩次運行之間是否會覆蓋舊的文件內容?這是因爲PrinteWriter覆蓋文件,請參閱https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter%28java.io.File%29或者您的問題是關於其他問題? – Robert

+0

羅伯特 - 我的文件總是被覆蓋,但我們應該在文件中存儲多個備忘錄。 –

回答

0
try { 
    Files.write(Paths.get("revisedLab25.txt"), ("the text"todayDate + "\n" + topic + "\n" + memo).getBytes(), StandardOpenOption.APPEND); 
}catch (IOException e) { 
    //exception handling 
} 

因爲你具有潛在的多次寫入爲用戶增加了輸入循環,你可以用一個Try-with-resources try塊寫操作。試用資源需要在離開試塊時關閉文件:

try(PrintWriter pw= new PrintWriter(new BufferedWriter(new FileWriter("revisedLab25.txt", true)))) { 

    do{ 
     while(!lab25){ 

     System.out.print("Enter the topic: "); 
     String topic = input.nextLine(); 

     Date date = new Date(); 
     String todayDate = date.toString(); 

     System.out.print("Message: "); 
     String memo = input.nextLine(); 

     pw.println(todayDate + "\n" + topic + "\n" + memo); 

     System.out.print("Do you want to continue(Y/N)?: "); 
     answer = input.next(); 
     } 

    }while(answer.equals("Y") || answer.equals("y")); 
} 
catch (IOException e) { 
    //exception handling 
}