Use the Randomaccessfile class to insert content at a specified file location

Source: Internet
Author: User

Package File;import Java.io.file;import Java.io.fileinputstream;import java.io.fileoutputstream;import Java.io.ioexception;import java.io.randomaccessfile;/* uses the Randomaccessfile class to insert content at the specified file location.  */public class Insertcontent {public static void insert (String fileName, Long pos, String insertcontent) throws IOException {File tmp = file.createtempfile ("tmp", null); Tmp.deleteonexit (); try (randomaccessfile RAF = new Randomaccessfile ( FileName, "RW"); FileOutputStream tmpout = new FileOutputStream (TMP); FileInputStream Tmpin = new FileInputStream (tmp)) {Raf.seek (POS); byte[] buf = new Byte[64];int Hasread = 0;while ((hasread = Raf.read (BUF)) >0) {tmpout.write (buf, 0, hasread);} Raf.seek (POS); Raf.write (Insertcontent.getbytes ()); while ((Hasread = Tmpin.read (buf)) >0) {raf.write (buf,0), Hasread);}}} public static void Main (string[] args) throws Ioexception{insert ("./src/file/insertcontent.java", 45, "Insert content!\n");}}

Use the Randomaccessfile class to insert content at the specified file location

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.