java - append 到文本文件,同时将存储的数据保留在文本文件中

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

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

DTR.txt pop-up

最佳答案

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

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

看看FileOutputStream了解更多详情

您可能还想看看try-catch-with-resources这将使您的生活更轻松

关于java - append 到文本文件,同时将存储的数据保留在文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41996053/

相关文章:

java 运算符与 boolean 操作数互斥

Eclipse:这些JSP错误是什么?

java - ByteArrayOutputStream的数据存储在哪里,RAM上还是硬盘上?

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

eclipse - 如何从 IDE 使用 Groovy 连接到本地或远程 Jenkins 实例?

java - 输入输出 : Writing and reading to the same text file from a C++ program and from another Java program simultaneously?

java - 应用程序在 1 小时后失去当前 Activity

java - Recyclerview 投入使用

java - 使用 java 8 stream api 做数组列表的深层复制但得到构建时间错误

java - 无法在 Eclipse 工作区中配置 Web 应用程序项目的运行路径