i got this code form the internet where it can delete a file.but when i tried to use it n my own java program it does not work anymore.it always returns 'Could not delete file'.
~this code is for my method delete
public void delete(String file, String lineToRemove) throws IOException{
try {
File inFile=new File("person.txt");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {}
}
public void run() throws IOException{
File file=new File("person.txt");
BufferedReader br=new BufferedReader(new FileReader(file));
while((str=br.readLine())!=null)
i++;
System.out.print("\t\t\t\t\t\t***************WELCOME*****************");
System.out.println();
System.out.println("1. Add \n2. Edit \n3. Delete \n4. Exit");
System.out.print("\nEnter option: ");
option=in.next();
while(true){
......
else if(option.charAt(0)=='3'){
FilingDatabase fd= new FilingDatabase();
System.out.print("Enter word: ");
String word=in.next();
fd.delete("person.txt",word);
}
......
}
}
~any help would be most appreciated.
~nesnes