import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;
public class LogFileSerializer {
/**
* Serializes a list of log file objects to a file.
* @param logFiles The list of log file objects to serialize.
* @param filePath The path to the file where the serialized data will be written.
* @param retryIntervalMillis The retry interval in milliseconds for dry-run scenarios.
* @throws IOException If an I/O error occurs during serialization.
*/
public static void serializeLogFiles(List<LogFile> logFiles, String filePath, long retryIntervalMillis) throws IOException {
// Create an ObjectOutputStream to write the serialized data to the file.
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
// Serialize the list of log files.
oos.writeObject(logFiles);
System.out.println("Log files serialized to: " + filePath);
}
}
/**
* Deserializes a list of log file objects from a file.
* @param filePath The path to the file containing the serialized data.
* @return The list of log file objects.
* @throws IOException If an I/O error occurs during deserialization.
*/
public static List<LogFile> deserializeLogFiles(String filePath) throws IOException {
List<LogFile> logFiles = null;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) {
logFiles = (List<LogFile>) ois.readObject();
System.out.println("Log files deserialized from: " + filePath);
} catch (ClassNotFoundException e) {
System.err.println("Class not found: " + e.getMessage());
}
return logFiles;
}
// Define a simple LogFile class for demonstration purposes.
public static class LogFile implements Serializable {
private String fileName;
private String content;
public LogFile(String fileName, String content) {
this.fileName = fileName;
this.content = content;
}
public String getFileName() {
return fileName;
}
public String getContent() {
return content;
}
@Override
public String toString() {
return "LogFile{" +
"fileName='" + fileName + '\'' +
", content='" + content + '\'' +
'}';
}
}
public static void main(String[] args) throws IOException {
// Example usage:
List<LogFile> logFiles = List.of(
new LogFile("app.log", "Application started"),
new LogFile("error.log", "An error occurred")
);
String filePath = "log_files.ser";
long retryInterval = 1000; // 1 second retry interval
serializeLogFiles(logFiles, filePath, retryInterval);
// Deserialize the log files.
List<LogFile> deserializedLogFiles = deserializeLogFiles(filePath);
System.out.println("Deserialized Log Files: " + deserializedLogFiles);
}
}
Add your comment