附加到文本文件,同时将存储的数据保留在TextFile

时间:2017-02-02 07:04:13

标签: java eclipse io append

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();
}

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

DTR.txt pop-up

1 个答案:

答案 0 :(得分:2)

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

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

请查看FileOutputStream了解更多详情

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