2016-04-06 14 views
2

私は、ユーザーが複数のメモをファイルに保存できるようにするプログラムを作成しました。私はPrintWriter &ファイルをJavaで使用する方法を考え出しましたが、私の問題は出力にあります。メモ帳でファイルをチェックすると、&の問題なしに1つのメモしか入力できません。メモは1つだけです。ここでは、コードです:PrintWriter&java in file

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

正確な問題は何ですか?あなたの古いファイルの内容は2回のプログラムの実行の間に上書きされますか?これは、PrinteWriterがファイルを上書きするためです。https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter%28java.io.File%29を参照してください? – Robert

+0

Robert - 私のファイルは常に上書きされますが、複数のメモをファイルに格納することになっています。 –

答えて

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-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 
}