Inserting text into an existing file via Java

I would like to create a simple program (in Java) which edits text files - particularly one which performs inserting arbitrary pieces of text at random positions in a text file. This feature is part of a larger program I am currently writing.

Reading the description about java.util.RandomAccessFile, it appears that any write operations performed in the middle of a file would actually overwrite the exiting content. This is a side-effect which I would like to avoid (if possible).

Is there a simple way to achieve this?

Thanks in advance.

Asked by: Walter452 | Posted: 21-01-2022

Answer 1

Okay, this question is pretty old, but FileChannels exist since Java 1.4 and I don't know why they aren't mentioned anywhere when dealing with the problem of replacing or inserting content in files. FileChannels are fast, use them.

Here's an example (ignoring exceptions and some other stuff):

public void insert(String filename, long offset, byte[] content) {
  RandomAccessFile r = new RandomAccessFile(new File(filename), "rw");
  RandomAccessFile rtemp = new RandomAccessFile(new File(filename + "~"), "rw");
  long fileSize = r.length();
  FileChannel sourceChannel = r.getChannel();
  FileChannel targetChannel = rtemp.getChannel();
  sourceChannel.transferTo(offset, (fileSize - offset), targetChannel);
  long newOffset = r.getFilePointer();
  sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset));

Answered by: Gianna928 | Posted: 22-02-2022

Answer 2

Well, no, I don't believe there is a way to avoid overwriting existing content with a single, standard Java IO API call.

If the files are not too large, just read the entire file into an ArrayList (an entry per line) and either rewrite entries or insert new entries for new lines.

Then overwrite the existing file with new content, or move the existing file to a backup and write a new file.

Depending on how sophisticated the edits need to be, your data structure may need to change.

Another method would be to read characters from the existing file while writing to the edited file and edit the stream as it is read.

Answered by: Ada527 | Posted: 22-02-2022

Answer 3

If Java has a way to memory map files, then what you can do is extend the file to its new length, map the file, memmove all the bytes down to the end to make a hole and write the new data into the hole.

This works in C. Never tried it in Java.

Another way I just thought of to do the same but with random file access.

  • Seek to the end - 1 MB
  • Read 1 MB
  • Write that to original position + gap size.
  • Repeat for each previous 1 MB working toward the beginning of the file.
  • Stop when you reach the desired gap position.

Use a larger buffer size for faster performance.

Answered by: Alina274 | Posted: 22-02-2022

Answer 4

You can use following code:

BufferedReader reader = null;
BufferedWriter writer = null;
ArrayList list = new ArrayList();

try {
    reader = new BufferedReader(new FileReader(fileName));
    String tmp;
    while ((tmp = reader.readLine()) != null)

    list.add(0, "Start Text");
    list.add("End Text");

    writer = new BufferedWriter(new FileWriter(fileName));
    for (int i = 0; i < list.size(); i++)
        writer.write(list.get(i) + "\r\n");
} catch (Exception e) {
} finally {

Answered by: Connie665 | Posted: 22-02-2022

Answer 5

I don't know if there's a handy way to do it straight otherwise than

  • read the beginning of the file and write it to target
  • write your new text to target
  • read the rest of the file and write it to target.

About the target : You can construct the new contents of the file in memory and then overwrite the old content of the file if the files handled aren't so big. Or you can write the result to a temporary file.

The thing would probably be easiest to do with streams, RandomAccessFile doesn't seem to be meant for inserting in the middle (afaik). Check the tutorial if you need.

Answered by: Clark955 | Posted: 22-02-2022

Answer 6

I believe the only way to insert text into an existing text file is to read the original file and write the content in a temporary file with the new text inserted. Then erase the original file and rename the temporary file to the original name.

This example is focused on inserted a single line into an existing file, but still maybe of use to you.

Answered by: Max591 | Posted: 22-02-2022

Answer 7

If it is a text file,,,,Read the existing file in StringBuffer and append the new content in the same StringBuffer now u can write the SrtingBuffer on file. so now the file contains both the existing and new text.

Answered by: David686 | Posted: 22-02-2022

Answer 8

As @xor_eq answer's edit queue is full, here in a new answer a more documented and slightly improved version of his:

public static void insert(String filename, long offset, byte[] content) throws IOException {
    File temp = Files.createTempFile("insertTempFile", ".temp").toFile(); // Create a temporary file to save content to
    try (RandomAccessFile r = new RandomAccessFile(new File(filename), "rw"); // Open file for read & write
            RandomAccessFile rtemp = new RandomAccessFile(temp, "rw"); // Open temporary file for read & write
            FileChannel sourceChannel = r.getChannel(); // Channel of file
            FileChannel targetChannel = rtemp.getChannel()) { // Channel of temporary file
        long fileSize = r.length();
        sourceChannel.transferTo(offset, (fileSize - offset), targetChannel); // Copy content after insert index to
                                                                                // temporary file
        sourceChannel.truncate(offset); // Remove content past insert index from file; // Goto back of file (now insert index)
        r.write(content); // Write new content
        long newOffset = r.getFilePointer(); // The current offset
        targetChannel.position(0L); // Goto start of temporary file
        sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset)); // Copy all content of temporary
                                                                                    // to end of file
    Files.delete(temp.toPath()); // Delete the temporary file as not needed anymore

Answered by: Jack687 | Posted: 22-02-2022

Similar questions

Inserting XML block into existing XML file in Java

I'm a bit of a newbie to XML. I have a class that creates an xml file (using Jaxb). So I have an existing xml file which contains the following. &lt;bookList&gt; &lt;book&gt; &lt;title&gt; Grapes of Wrath &lt;/title&gt; &lt;author&gt; John Steinbeck &lt;/author&gt; &lt;/book&gt; &lt;book&gt; &lt;title&gt; Harry Potter &lt;/title&gt; &lt;author&gt; J.K. Rowling &lt;/author&gt; &lt;/bo...

java - Inserting value in DB or update existing one

I'm trying to manage my DB with EclipseLink and I've got a serious problem. Here's my simple method PUEntityManager.getTransaction().begin(); if (!PUEntityManager.contains(evento)) { PUEntityManager.persist(evento); } else { PUEntityManager.merge(evento); //PUEntityManager.refresh(evento); } PUEntityManager.getTransaction().commit();

java - inserting existing PDF into one being created, iText 2

I have a web application using iText v2.1.7 to create PDFs; before anyone tries to move me to a different library, let me point out that, like most programmers, I don't choose the libraries my company uses for things, or I certainly would not use this one. I have code that generates these PDFs; now I am to add code that takes the contents of an existing PDF and inserts it into the PDF I'm creating. I've fou...

apache poi - Inserting new column in existing xls file keeping the format intact In Java

I want to insert a new column in between the existing columns of the excel which is in .xls format using Java retaining the existing format. Is there any api to do so?

sql - Java: creating a date object from a string and inserting into MySQL

Anytime I have to handle dates/times in java it makes me sad I'm trying to parse a string and turn it into a date object to insert in a preparepared statement. I've been trying to get this working but am having no luck. I also get the helpful error message when I go to compile the class. "Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method setDate(int, Date) in the type ...

java - Repeated values when inserting rows into JTable

I have problems on inserting rows into a JTable and I don't know what the problem is. I do exactly like this: ((DefaultTableModel)myJTable.getModel()).insertRow(0,webSiteDownloader.getWebSites().toArray()); The webSiteDownloader is one object that have an ArrayList. I can get that array calling the method getWebSites. The ...

java - iText - inserting overlay text on top of all elements

Using the iText PDF library, is it possible to freely (like "position: absolute" in CSS) insert overlay text or other elements on page, so that it gets rendered on top of all existing elements? Thanks for all the help and tips in advance.

MySQL Inserting large data sets from file with Java

I need to insert about 1.8 million rows from a CSV file into a MySQL database. (only one table) Currently using Java to parse through the file and insert each line. As you can imagine this takes quite a few hours to run. (10 roughtly) The reason I'm not piping it straight in from the file into the db, is the data has to be manipulated before it adds it to the database. This process needs...

sql - Postgres encoding "UTF8" error whilst inserting images via Java

I am inserting jpeg images into my UTF-8 encoded Postgres database into bytea column/s. I'm using a prepared sql statement to insert the images. In the statement I create a file object, within Java, of the jpeg image and then pass it as a FileInputStream into the setBinaryStream method. However every now and again my Java app will throw an exception once the statement is executed, stating that: " ERROR: invalid byt...

java - Javadoc Inserting UML Diagrams

Is there a way to embed images into my JavaDoc? Basically i want to include some UML diagrams explaining the hierarchy of my classes in some of the documentation. Thanks!

java inserting date into database

can someone please tell me the elegant way of inserting a java date instance into database? presently, i am using IBATIS with Spring MVC . i have defined a property in the command bean and property editor in the controller for Date conversion, however i am unable to insert property in DB . should i convert this into instance inorder to store in DB? if i h...

java - Inserting Username token in security header of already generated SOAP envelope gives me two headers!

I'm using WSS4J to add a Username token in the header of an already formed SOAP request envelope. Here is what the SOAP request looks like: &lt;soapenv:Envelope xmlns:soapenv="" xmlns:xsd=""&gt; &lt;soapenv:Header/&gt; &lt;soapenv:Body&gt; &lt;xsd:echo&gt; &lt;xsd:param0...

Inserting string array value in for loop in java

I know this is a very simple thing, but I can't see any examples of doing this with strings. This is beyond the basic exercise in my self imposed homework, and more advanced, but I know it can be done so I just want to go ahead and learn these arrays :-D I'm trying to change the value if the string in the GLabel below: private void printSubclassBoxes(){ String[] anArray = {"GraphicsProgram"...

java - Inserting the record into Database through JPA

In my code I am using JSF - Front end , EJB-Middile Tier and JPA connect to DB.Calling the EJB using the Webservices.Using MySQL as DAtabase. I have created the Voter table in which I need to insert the record. I ma passing the values from the JSF to EJB, it is working.I have created JPA controller class (which automatcally generates the persistence code based on the data base classes) Ex: getting the entity manager etc.,

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)