Java File Modification: Complete Guide
In Java, you can use FileInputStream and FileOutputStream to read and write file data. Below is a simple example code that can be used to modify data in a file:
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();
}
}
}
In this example, the file content is first read into a byte array using FileInputStream, then the data that needs to be modified is replaced in the array, and finally the modified data is written back to the file using FileOutputStream.