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 到文本文件而不影响文本文件中存储的数据?这只是我的代码的摘录。上面的方法应该在每个循环中在文本文件中输入时间和超时时间,但它只会替换文本文件中存储的数据。这总是会弹出。
最佳答案
使用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/