Sethoy Sethoy - 4 years ago 127
Java Question

Appending to a Textfile while keeping the stored data in the TextFile

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


How can I append to a textfile while not affecting the stored data in the textfile? this is only an excerpt of my codes. The method above should input the time in and time out hour in the textfile every loop but it only replaces the stored data in the textfile. This always pop up.

DTR.txt pop-up

Answer Source

Use a FileOutpuStream to setup the stream, this will allow to specify that you want to append to the current file

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

Have a look at FileOutputStream for more deatils

You may also like to take a look at try-catch-with-resources which will help make your life easier

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download