Java Modify file Contents

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.