/** * Reads the content of a file and tries to parse it as JSON into an object. * * @param file The file on disk to read from. * @param classOfValue The class definition that the JSON should be parsed into. * @return The object stored in the file. * @throws IOException If anything went wrong during file access. */ protected static <E> E readObjectFromDisk(File file, Class<E> classOfValue) throws IOException { // Validate file. if (!isReadableFile(file)) { return null; } if (classOfValue == null || classOfValue.equals(Void.class)) { return null; } long length = file.length(); if (length < 0 || length > Integer.MAX_VALUE) { return null; } // Read from disk. byte[] bytes = new byte[(int) length]; FileInputStream fileInputStream = new FileInputStream(file); try { fileInputStream.read(bytes); } finally { fileInputStream.close(); } // Parse JSON to object. String json = new String(bytes); E result = JsonParser.fromJson(json, classOfValue); return result; }
/** * Tries to write the value to the disk store. An attempt will be made to parse the value to JSON * and on success it will be written to a file with the same name as the key. The key will be * transformed to the file name by calling the <code>toString()</code> method on it (pick your * keys with great care). * * @param file The {@link File} pointing at the desired destination file on disk. * @param value The value that will be serialized to JSON and saved as a file. * @throws IOException */ protected static void writeObjectToDisk(File file, Object value) throws IOException { String json = JsonParser.toJson(value); FileOutputStream fileOutputStream = new FileOutputStream(file); try { fileOutputStream.write(json.getBytes()); } finally { fileOutputStream.close(); } }