java - Deleting certain data from a file -


i have file stored in system , want delete data it.

i accomplish making temporary file, write of original file data it, without data don't want. then, rename temporary file same name of original file in order replace it.

everything goes well, except there problem deleting original file , renaming temporary file.

at first, had original file data, after running application had original file same data without deletion, , temporary file named (file) data after deletion.

here's method i'm using:

public void remove(string path, string link, string ext) throws ioexception {      file file = new file(path);     file temp = file.createtempfile("file", ext, file.getparentfile());     string charset = "utf-8";     bufferedreader reader = new bufferedreader(new inputstreamreader(new fileinputstream(file), charset));     printwriter writer = new printwriter(new outputstreamwriter(new fileoutputstream(temp), charset));      (string line; (line = reader.readline()) != null; ) {         line = line.replace(link, "");         writer.println(line);     }      reader.close();     writer.close();     file.delete();     temp.renameto(file); } 

you want check return value of delete(). if old file doesn't deleted, prevent renaming new file. if old file may still openend other services or don't have right permissions, try rename path + ".old" before deleting it. might move out of way if can't deleted. try file.setwriteable(true). depends on why file can't deleted.

also, depending on system setup, temp file may created in location require move instead of rename (i.e. not on same file system), renameto() doesn't work.

to address this, don't create temp file. not temp file -- it's permanent after rename. instead, create regular file in same directory original file, i.e.

file temp = new file(path + ".tmp"); 

this make sure both files on same file system , rename work.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -