【问题标题】:PrintWriter & File in javaJava中的PrintWriter和文件
【发布时间】: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


【解决方案1】:
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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多