【问题标题】:Appending to a Textfile while keeping the stored data in the TextFile附加到文本文件,同时将存储的数据保留在文本文件中
【发布时间】:2017-06-19 03:51:18
【问题描述】:
public static void InandOut() {


    Scanner scnThree = new Scanner(System.in);
    String days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};

    for(int iNum = 0; iNum < days.length; iNum++){
        System.out.printf("Enter time-in for %s: ", days[iNum]);
        timein = scnThree.nextLine();
        System.out.printf("Enter time-out for %s: ", days[iNum]);
        timeout = scnThree.nextLine();

        String strIn[] = timein.split(":");
        float intIn[] = new float[strIn.length];

        for(int i = 0; i < intIn.length; i++) {
            intIn[i] = Integer.parseInt(strIn[i]);
        }

        float minutesIn = intIn[1] / 60;
        float hoursIn = intIn[0] + minutesIn;

        String strOut[] = timeout.split(":");
        float intOut[] = new float[strOut.length];

        for(int i = 0; i < intOut.length; i++){
            intOut[i] = Integer.parseInt(strOut[i]);
        }

        float minutesOut = intOut[1] / 60;
        float hoursOut = intOut[0] + minutesOut;

        late = hoursIn - 8;
        undertime = 17 - hoursOut;
        dailyworkhours = 8 - (late + undertime);
        totalLate += late;
        totalUndertime += undertime;
        totalNumberofWorkHours += dailyworkhours;



        try{
            oFile = new Formatter("DTR.txt");
        }catch(Exception e){
            System.out.println("You've got an error!");
        }

        oFile.format("\n%s\t %s\t %s", days[iNum], timein, timeout);

        oFile.close();
    }

    System.out.print("Enter the coverage date of this payroll: ");
    coverDate = scnThree.nextLine();
}

如何在不影响文本文件中存储的数据的情况下附加到文本文件?这只是我的代码的摘录。上面的方法应该在每个循环的文本文件中输入时间和超时时间,但它只替换文本文件中存储的数据。这总是弹出。

【问题讨论】:

  • A FileWriter 有一个构造函数 FileWriter(File file, boolean append),您必须将 append 设置为 true
  • 如果在编辑器打开时在 Eclipse 外部更改文本文件,您将始终从 Eclipse 文本编辑器中获得消息。

标签: java eclipse io append


【解决方案1】:

使用FileOutpuStream 设置流,这将允许指定要附加到当前文件

    try (Formatter oFile = new Formatter(new FileOutputStream("DTR.txt", true))) {
        //...
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }

查看FileOutputStream了解更多详情

您可能还想看看try-catch-with-resources,这将有助于让您的生活更轻松

【讨论】:

    猜你喜欢
    • 2015-02-04
    • 2021-08-18
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 2015-03-03
    • 1970-01-01
    • 2011-02-24
    相关资源
    最近更新 更多