Java 如何在特定索引处修改或更新包含少量内容更改的大型文件

Java 如何在特定索引处修改或更新包含少量内容更改的大型文件,java,file,file-io,Java,File,File Io,我需要修改一个文件。我们已经编写了一个相当复杂的组件来构建一组索引来描述文件中感兴趣的内容,但是现在我需要使用这组索引来编辑这个文件,这很困难 具体来说,我的DreamAPI是这样的 //if you'll let me use kotlin for a second, assume we have a simple tuple class data class IdentifiedCharacterSubsequence { val indexOfFirstChar : int, val ex

我需要修改一个文件。我们已经编写了一个相当复杂的组件来构建一组索引来描述文件中感兴趣的内容,但是现在我需要使用这组索引来编辑这个文件,这很困难

具体来说,我的DreamAPI是这样的

//if you'll let me use kotlin for a second, assume we have a simple tuple class
data class IdentifiedCharacterSubsequence { val indexOfFirstChar : int, val existingContent : String }

//given these two structures 
List<IdentifiedCharacterSubsequences> interestingSpotsInFile = scanFileAsPerExistingBusinessLogic(file, businessObjects);
Map<IdentifiedCharacterSubsequences, String> newContentByPreviousContentsLocation = generateNewValues(inbterestingSpotsInFile, moreBusinessObjects);

//I want something like this:
try(MutableFile mutableFile = new com.maybeGoogle.orApache.MutableFile(file)){

    for(IdentifiedCharacterSubsequences seqToReplace : interestingSpotsInFile){

        String newContent = newContentByPreviousContentsLocation.get(seqToReplace);

        mutableFile.replace(seqToReplace.indexOfFirstChar, seqtoReplace.existingContent.length, newContent);
        //very similar to StringBuilder interface
        //'enqueues' data changes in memory, doesnt actually modify file until flush call...
    }

    mutableFile.flush();
    // ...at which point a single write-pass is made.
    // assumption: changes will change many small regions of text (instead of large portions of text) 
    // -> buffering makes sense
}
//如果让我用一下kotlin,假设我们有一个简单的元组类
数据类IdentifiedCharacterSubsequence{val indexOfFirstChar:int,val existingContent:String}
//鉴于这两种结构
List interestingSpotsInFile=scanFileAsPerExistingBusinessLogic(文件,businessObjects);
映射newContentByPreviousContentsLocation=generateNewValues(InTerestingSpotsinFile,moreBusinessObjects);
//我想要这样的东西:
try(MutableFile MutableFile=new com.maybeGoogle.orApache.MutableFile(文件)){
for(IdentifiedCharacterSubsequences seqToReplace:InterestingsSpotsinFile){
字符串newContent=newContentByPreviousContentsLocation.get(seqToReplace);
替换(seqToReplace.indexOfFirstChar、seqToReplace.existingContent.length、newContent);
//非常类似于StringBuilder界面
//“排队”内存中的数据更改,在刷新调用之前不会实际修改文件。。。
}
mutableFile.flush();
//…此时进行一次写入过程。
//假设:更改将更改文本的许多小区域(而不是文本的大部分)
//->缓冲是有意义的
}
一些注意事项:

  • 我无法使用
    RandomAccessFile
    ,因为我的更改不到位(
    newContent
    的长度可能比
    seq.existingContent
    的长度长或短)
  • 这些文件通常有很多兆字节大,因此简单地将整个文件读入内存并将其修改为数组是不合适的
这样的东西是否存在,或者我是否已沦落为使用BufferedWriter之类的工具编写自己的实现?对于一种通常非常强调基于索引的行为的语言来说,
io.Streams
似乎是一种明显的演变,但我找不到现有的实现

最后:我对文件和编码方案的领域经验很少,因此我没有努力解决以下问题中描述的“两个索引”字符:。在此方面的任何帮助都将不胜感激。这就是为什么我找不到这样一个实现的原因吗?因为UTF-8编码文件中的索引非常烦人且容易出现错误