Colin Seng Colin Seng - 29 days ago 12
Java Question

Why is the file not being deleted in this java program?

Below code reads and then write into a separate file.

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import static java.lang.System.out;

public class arrays_2 {

public static void main(String args[])
throws FileNotFoundException{

Scanner diskScanner = new Scanner(new File("C://Users//Colin//workspace_dreamvision//Genesis//src//occupancy.txt"));
Scanner keyboard = new Scanner(System.in);
PrintStream diskWriter = new PrintStream("C://Users//Colin//workspace_dreamvision//Genesis//src//occupancy2.txt");
int guestsIn[] = new int [10];
int numGuests, roomNum = 0;
char reply;

out.print ("Have all the guest(s) left? (Y / N) ");
reply = keyboard.findWithinHorizon(".",0).charAt(0);
out.print("\n");

if (reply == 'Y' || reply == 'y'){
for(; roomNum < 10; roomNum++){
guestsIn[roomNum] = 0;
}
}

do {
out.print("Room Number: ");
roomNum = keyboard.nextInt();
out.print("How many guests? ");
numGuests = keyboard.nextInt();
guestsIn[roomNum] = numGuests;
out.print("Do another? ");
reply = keyboard.findWithinHorizon(".",0).charAt(0);
out.print("\n");
} while (reply == 'Y' || reply == 'y');

out.println("Room\tGuests");

for (roomNum = 0; roomNum < 10; roomNum++){
out.print(roomNum);
out.print("\t");
out.println(guestsIn[roomNum]);
}

for (int howMany : guestsIn){
diskWriter.print(howMany + " ");
}


From the code below, it should delete the file in the directory path below.

new File ("C://Users//Colin//workspace_dreamvision//Genesis//src//occupancy.txt").delete();

diskScanner.close();
keyboard.close();
diskWriter.close();

}
}


At end of this code, I checked occupancy.txt file is still in the directory. Please help.

Answer

You have to close your scanner before deleting your file

Comments