import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class FileModifier {

    // 修改INI文件（替换包含someSetting的行）
    public static void modifyIniFile(String filePath) {
        // 读取原文件内容
        List<String> lines = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8))) {
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            System.err.println("读取INI文件失败：" + e.getMessage());
            return;
        }

        // 写入修改后内容
        try (BufferedWriter bw = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8))) {
            for (String line : lines) {
                // 若行包含someSetting，替换为新值
                if (line.contains("someSetting")) {
                    bw.write("someSetting=newValue");
                } else {
                    bw.write(line);
                }
                bw.newLine(); // 保持行分隔
            }
            System.out.println("INI文件修改完成");
        } catch (IOException e) {
            System.err.println("写入INI文件失败：" + e.getMessage());
        }
    }

    // 修改SAV文件（替换前4字节为0x01020304）
    public static void modifySavFile(String filePath) {
        try (RandomAccessFile raf = new RandomAccessFile(filePath, "rw")) {
            // 读取前4字节（与Python的read(4)对应，仅做演示，原代码未使用读取结果）
            byte[] originalData = new byte[4];
            raf.read(originalData);

            // 回到文件开头，写入新的4字节
            raf.seek(0);
            raf.write(new byte[]{0x01, 0x02, 0x03, 0x04});
            System.out.println("SAV文件修改完成");
        } catch (IOException e) {
            System.err.println("修改SAV文件失败：" + e.getMessage());
        }
    }

    public static void main(String[] args) {
        String iniFilePath = "path/to/your/file.ini"; // 替换为实际INI文件路径
        String savFilePath = "path/to/your/file.sav"; // 替换为实际SAV文件路径

        modifyIniFile(iniFilePath);
        modifySavFile(savFilePath);
    }
}
