Java ファイルデータ変更:基本と実践テクニック

Javaでは、ファイルデータを読み込み、書き込むためにFileInputStreamとFileOutputStreamを使用することができます。次に示すのは、ファイルのデータを変更するための簡単なサンプルコードです:

import java.io.*;

public class ModifyFileData {

    public static void main(String[] args) {
        try {
            File file = new File("example.txt");
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fis.read(data);
            fis.close();

            // 修改文件数据
            String newData = "New data to be written to the file";
            byte[] newDataBytes = newData.getBytes();
            System.arraycopy(newDataBytes, 0, data, 0, newDataBytes.length);

            FileOutputStream fos = new FileOutputStream(file);
            fos.write(data);
            fos.close();

            System.out.println("File data has been modified successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

この例では、まずFileInputStreamを使用してファイルの内容をバイト配列に読み込み、その後、変更するデータを配列に置き換え、最後にFileOutputStreamを使用して変更後のデータをファイルに書き込みます。

bannerAds