Heim  >  Fragen und Antworten  >  Hauptteil

io - Java-Dateioperation, wie füge ich Inhalte an einem bestimmten Ort ein (nicht ersetze Inhalte)?

Java-Dateioperation, wie füge ich Inhalte an einem bestimmten Ort ein (ersetze Inhalte nicht)?

大家讲道理大家讲道理2686 Tage vor813

Antworte allen(2)Ich werde antworten

  • phpcn_u1582

    phpcn_u15822017-06-12 09:26:18

    不存在真正意义上的插入文件,因为文件大小是确定的。所以只能用临时文件去替换源文件。

    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);
      sourceChannel.truncate(offset);
      r.seek(offset);
      r.write(content);
      long newOffset = r.getFilePointer();
      targetChannel.position(0L);
      sourceChannel.transferFrom(targetChannel, newOffset, (fileSize - offset));
      sourceChannel.close();
      targetChannel.close();
    }
    

    https://stackoverflow.com/que...

    Antwort
    0
  • 怪我咯

    怪我咯2017-06-12 09:26:18

    你参考下这个:

    https://faceghost.com/questio...

    Antwort
    0
  • StornierenAntwort