The reading and writing of documents, everyone is not strange, but modify it? According to the normal read and write stream to modify, can only read out, in memory modified, all written in, so for the file content too much, performance is very low.
Recently encountered this problem, found that randomaccessfile this class just can solve my problem, nonsense not much to say, the following direct code, share to everyone, there is no place to welcome advice, Thank you
/**
* Modify the contents of the file
* @param fileName
* @param oldstr
* @param newstr
* @return
*/
private static Boolean modifyfilecontent (String fileName, String oldstr, String newstr) {
Randomaccessfile RAF = null;
try {
RAF = new Randomaccessfile (filepath+ "/" +filename, "RW");
String line = null;
Long lastpoint = 0; Remember the last offset
while (line = Raf.readline ()) = null) {
Final Long ponit = Raf.getfilepointer ();
if (Line.contains (OLDSTR)) {
String str=line.replace (Oldstr, NEWSTR);
Raf.seek (Lastpoint);
Raf.writebytes (str);
}
Lastpoint = Ponit;
}
} catch (Exception e) {
E.printstacktrace ();
} finally {
try {
Raf.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
return true;
}
Java Modify file Contents