Forum Stats

  • 3,873,719 Users
  • 2,266,633 Discussions


In Java, how do you insert, change, and remove file regions?

User_SQDZD Member Posts: 9 Green Ribbon

I'm searching for a Java class that manages text addition, replacement, and deletion for an existing file in the same way as StringBuilder does.

I don't want to use a StringBuilder since I don't want to keep the entire file in memory.

The goal is to apply patches to a file containing code written in any programming language.



  • User_SQDZD
    User_SQDZD Member Posts: 9 Green Ribbon
    edited Jul 29, 2022 11:03AM

    While searching for answers I found out that we may change the existing StringBuilder sequence in two ways: we can delete certain components of the series or we can introduce text into the StringBuilder sequence. This article, (here) suggested that StringBuilder.insert(index,text) method can be used to insert text at the specified index.

  • JerryDAndrews-Oracle
    JerryDAndrews-Oracle Kingston, WA, USPosts: 1 Employee

    You have basically 2 options:

    1. stream the file, making changes as you go, and write it back out as you read it in, or
    2. load the file into memory, make changes, and write it back out.

    If you're working with source files, you're going to be working with files that should be less than a few thousand lines long each--so loading them into memory doesn't consume very much, and gives you a lot of flexibility.

    If you insist on streaming the files and editing on the fly, your particular use cases are going to determine how big each chunk should be, so there's probably no general solution available. There are samples available on stack overflow, e.g., for the streaming approach.

    Why do you feel it's important not to load each file into memory?