package com.intel.daal.examples.serialization;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.intel.daal.data_management.data.NumericTable;
import com.intel.daal.data_management.data_source.DataSource;
import com.intel.daal.data_management.data_source.FileDataSource;
import com.intel.daal.examples.utils.Service;
import com.intel.daal.services.DaalContext;
class SerializationExample {
private static final String dataset = "../data/batch/serialization.csv";
private static DaalContext context = new DaalContext();
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
FileDataSource dataSource = new FileDataSource(context, dataset,
DataSource.DictionaryCreationFlag.DoDictionaryFromContext,
DataSource.NumericTableAllocationFlag.DoAllocateNumericTable);
dataSource.loadDataBlock();
NumericTable dataTable = dataSource.getNumericTable();
Service.printNumericTable("Data before serialization:", dataTable);
byte[] buffer = serializeNumericTable(dataTable);
NumericTable restoredDataTable = deserializeNumericTable(buffer);
Service.printNumericTable("Data after deserialization:", restoredDataTable);
context.dispose();
}
private static byte[] serializeNumericTable(NumericTable dataTable) throws IOException {
ByteArrayOutputStream outputByteStream = new ByteArrayOutputStream();
ObjectOutputStream outputStream = new ObjectOutputStream(outputByteStream);
dataTable.pack();
outputStream.writeObject(dataTable);
byte[] buffer = outputByteStream.toByteArray();
return buffer;
}
private static NumericTable deserializeNumericTable(byte[] buffer) throws IOException, ClassNotFoundException {
ByteArrayInputStream inputByteStream = new ByteArrayInputStream(buffer);
ObjectInputStream inputStream = new ObjectInputStream(inputByteStream);
NumericTable restoredDataTable = (NumericTable) inputStream.readObject();
restoredDataTable.unpack(context);
return restoredDataTable;
}
}