【发布时间】:2016-04-06 02:07:46
【问题描述】:
我编写了一个程序,允许用户将多个备忘录存储在一个文件中。我想出了如何在 Java 中使用 PrintWriter & 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:
如何更改它,以便输出允许我继续存储备忘录,直到我告诉它停止?
【问题讨论】:
-
具体的问题是什么?您的旧文件内容是否在 2 次程序运行之间被覆盖?那是因为 PrinteWriter 覆盖了一个文件,请参阅docs.oracle.com/javase/7/docs/api/java/io/… 或者您还有其他问题?
-
Robert - 我的文件总是被覆盖,但我们应该在一个文件中存储多个备忘录。
标签: java eclipse file printwriter