how to update certain parts of text file in java -
i want able update line on text file. error cannot delete file, why error?
public class main { public static void main(string[] args) { main rlf = new main(); rlf.removelinefromfile("f:\\text.txt", "bbb"); } public void removelinefromfile(string file, string linetoremove) { try { file infile = new file(file); if (!infile.isfile()) { system.out.println("parameter not existing file"); return; } //construct new file later renamed original filename. file tempfile = new file(infile.getabsolutepath() + ".tmp"); bufferedreader br = new bufferedreader(new filereader(file)); printwriter pw = new printwriter(new filewriter(tempfile)); string line = null; //read original file , write new //unless content matches data removed. while ((line = br.readline()) != null) { if (!line.trim().equals(linetoremove)) { pw.println(line); pw.flush(); } } pw.close(); br.close(); //delete original file if (!infile.delete()) { system.out.println("could not delete file"); return; } //rename new file filename original file had. if (!tempfile.renameto(infile)) system.out.println("could not rename file"); } catch (filenotfoundexception ex) { ex.printstacktrace(); } catch (ioexception ex) { ex.printstacktrace(); } } }
the program works me. perhaps having environmental issue.
Comments
Post a Comment