Skip to content

Instantly share code, notes, and snippets.

@emabrey
Last active May 5, 2018 06:04
Show Gist options
  • Save emabrey/a317a5b15bf60a38cb87a826bce0f38a to your computer and use it in GitHub Desktop.
Save emabrey/a317a5b15bf60a38cb87a826bce0f38a to your computer and use it in GitHub Desktop.
Single file class/program for POC of a Stack Overflow answer
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamConstants;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
/**
* This is a "test" program for testing the method I wrote for a StackOverflow answer here:
* <p>
* https://stackoverflow.com/questions/50124409/using-generic-arraylist-as-parameter/50124491#50124491
* <p>
* Please forgive the lack of code documentation/Javadoc as this was just a short POC and not intended as production
* quality code.
*
* @author Emily Mabrey <[email protected]>
*/
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public class ObjectInputExample {
/**
* For a given file at the specified path, attempts to deserialize and return an Object instance specified via
* the various generic types.
* @param type The Class representing the stored Object type within the serialized object graph
* @param fileName The path of the file to deserialize
* @param <OUTPUT> The return type expected by the caller
* @param <INPUT> The type of the object stored within the serialized object graph
* @return The deserialized object. If it returns null the null was checked for type-safety as far as possible.
*
* @throws IOException Means the file IO failed
* @throws ClassNotFoundException Means the casting of serialized objects failed
*/
public static <OUTPUT extends Serializable, INPUT extends Serializable>
OUTPUT getObjectFromFile(Class<INPUT> type, CharSequence fileName)
throws IOException, ClassNotFoundException {
final String filenameString = Objects.requireNonNull(fileName).toString();
final Class<INPUT> inputType = Objects.requireNonNull(type);
try (ObjectInput ois = new ObjectInputStream(new FileInputStream(filenameString))) {
final Object rawObject = ois.readObject();
@SuppressWarnings("unchecked")
final OUTPUT output = (OUTPUT) (rawObject == null ? null : inputType.cast(rawObject));
return output;
}
}
/**
* For a given file at the specified path, attempts to deserialize and add an Object instance specified via
* the various generic types into the given Collection.
*
* @param out The Collection which can accept the deserialized object
* @param type The Class representing the stored Object type within the serialized object graph
* @param fileName The path of the file to deserialize
* @param <DESIRED> The element type for the output Collection
* @param <STORED> The Object type of the deserialized Object
* @return A boolean representing successful loading of a serialized Object via true; failure is false.
*
* @throws IOException Means the file IO failed
* @throws ClassNotFoundException Means the casting of serialized objects failed
*/
public static <DESIRED extends Serializable, STORED extends Serializable>
boolean addArrayListFromFile(Collection<DESIRED> out, Class<STORED> type, CharSequence fileName)
throws IOException, ClassNotFoundException {
@SuppressWarnings("unchecked")
final ArrayList<DESIRED> inList = getObjectFromFile(type, fileName);
return inList != null && out.addAll(inList);
}
public static void main(String[] in) {
final ArrayList<String> testList = new ArrayList<>(1);
testList.add("Test strings should never string you along...");
testList.add("Test String 2!!!");
final ArrayList<String> resultList = new ArrayList<>(1);
final StringBuilder tempFileBuffer = new StringBuilder(50);
try {
final String resultAbsolutePath = createFilenameAsTempFile(testList);
tempFileBuffer.append(resultAbsolutePath);
tempFileBuffer.trimToSize();
}
catch (Throwable t) {
System.out.println("Unable to generate test file");
t.printStackTrace(System.out);
System.exit(0);
}
try {
String tempFile = tempFileBuffer.toString();
System.out.printf("Temp File: %s%n%n", tempFile);
final boolean result = addArrayListFromFile(resultList, ArrayList.class, tempFile);
System.out.printf("Method reports it correctly generated output: %s%n", result);
}
catch (Throwable t) {
System.out.println("Calling method generated an error");
t.printStackTrace(System.out);
System.exit(0);
}
System.out.printf("Method actually did correctly generate output: %s%n%n", testList.equals(resultList));
System.out.printf("Encoding Input: %s%n", testList);
System.out.printf("Decoding Output: %s%n", resultList);
}
/**
* Quick and dirty way to generate temporary output file.
*
* @param testList The list of objects to serialize and write to the file
* @return A String containing the absolute file location of a temporary file
* @throws IOException If the file creation or the streams fail to write or initialize
*/
private static <T extends Serializable> String createFilenameAsTempFile(final List<T> testList) throws IOException {
File outFile = File.createTempFile("test-", ".ser");
outFile.deleteOnExit();
try (FileOutputStream fos = new FileOutputStream(outFile);
ObjectOutputStream oos = new ObjectOutputStream(fos))
{
oos.useProtocolVersion(ObjectStreamConstants.PROTOCOL_VERSION_2);
oos.writeObject(testList);
return outFile.getAbsolutePath();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment