package com.shadowninja108.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Iterator;
public class RawFileEditor {
private RandomAccessFile file;
ArrayList<FileModification> modifications;
public RawFileEditor(File file) {
try {
this.file = new RandomAccessFile(file, "rw");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
modifications = new ArrayList<>();
}
/**
* Add a modification to queue.
*
* @param location
* where to modify the file
* @param bytes
* what to overwrite in the file
*/
public void write(long location, byte[] bytes) {
modifications.add(new FileModification(location, bytes));
}
/**
* Write all stored modifications to file. This also clears the modification
* storage. Safe to call if empty.
*
*/
public void save() {
try {
Iterator<FileModification> it = modifications.iterator();
while (it.hasNext()) {
FileModification next = it.next();
if ((next.location + next.bytes.length) < file.length()) {
file.seek(next.location);
file.write(next.bytes);
System.out.println("Wrote " + next.bytes.length + " bytes at " + next.location);
} else
System.out.println("Attempted to write outside file!");
}
} catch (IOException e) {
e.printStackTrace();
}
modifications.clear();
}
public class FileModification {
public long location;
public byte[] bytes;
public FileModification(long location, byte[] bytes) {
this.location = location;
this.bytes = bytes;
}
}
}