From de39f6031432fa5f7cce7eea099308764a22e418 Mon Sep 17 00:00:00 2001 From: Joel Therrien Date: Fri, 14 Sep 2018 14:53:01 -0700 Subject: [PATCH] Make CovariateRow's serializable; add R utility functions. --- .../randomforest/CovariateRow.java | 3 +- .../randomforest/utils/RUtils.java | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/main/java/ca/joeltherrien/randomforest/CovariateRow.java b/src/main/java/ca/joeltherrien/randomforest/CovariateRow.java index 2b664b8..c8e2543 100644 --- a/src/main/java/ca/joeltherrien/randomforest/CovariateRow.java +++ b/src/main/java/ca/joeltherrien/randomforest/CovariateRow.java @@ -4,12 +4,13 @@ import ca.joeltherrien.randomforest.covariates.Covariate; import lombok.Getter; import lombok.RequiredArgsConstructor; +import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; @RequiredArgsConstructor -public class CovariateRow { +public class CovariateRow implements Serializable { private final Map valueMap; diff --git a/src/main/java/ca/joeltherrien/randomforest/utils/RUtils.java b/src/main/java/ca/joeltherrien/randomforest/utils/RUtils.java index 419f20f..2ee3cb4 100644 --- a/src/main/java/ca/joeltherrien/randomforest/utils/RUtils.java +++ b/src/main/java/ca/joeltherrien/randomforest/utils/RUtils.java @@ -1,6 +1,9 @@ package ca.joeltherrien.randomforest.utils; +import java.io.*; import java.util.List; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; /** * These static methods are designed to make the R interface more performant; and to avoid using R loops. @@ -30,5 +33,33 @@ public final class RUtils { return times; } + /** + * Convenience method to help R package serialize Java objects. + * + * @param object The object to be serialized. + * @param filename The path to the object to be saved. + * @throws IOException + */ + public static void serializeObject(Serializable object, String filename) throws IOException { + final ObjectOutputStream outputStream = new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(filename))); + outputStream.writeObject(object); + outputStream.close(); + } + + /** + * Convenience method to help R package load serialized Java objects. + * + * @param filename The path to the object saved. + * @throws IOException + */ + public static Object loadObject(String filename) throws IOException, ClassNotFoundException { + final ObjectInputStream inputStream = new ObjectInputStream(new GZIPInputStream(new FileInputStream(filename))); + final Object object = inputStream.readObject(); + inputStream.close(); + + return object; + + } + }