Created
January 27, 2016 07:23
-
-
Save Grumblesaur/e23e0bac257fda3f67eb to your computer and use it in GitHub Desktop.
Found in a young Java fanatic's dropbox. Reinventing the ObjectOutputStream wheel.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static void put(Preferences prefs, String key, byte[] bytes) { | |
final int maxBytesPerKey = byteArrLen(); | |
final int keysNeeded = (int) Math.ceil((float) bytes.length / (float) maxBytesPerKey); | |
final int remainderBytes = bytes.length % maxBytesPerKey; | |
byte[][] splitBytes = new byte[keysNeeded][maxBytesPerKey]; | |
splitBytes[keysNeeded-1] = new byte[remainderBytes]; | |
for (int keyNum=0; keyNum < keysNeeded; keyNum++) { | |
for (int b=0; b < splitBytes[keyNum].length; b++) { | |
splitBytes[keyNum][b] = bytes[(keyNum * maxBytesPerKey) + b]; | |
} | |
} | |
// splitBytes now populated properly | |
prefs.putInt("keys", keysNeeded); | |
prefs.putInt("bytes", (keysNeeded * (maxBytesPerKey-1)) + remainderBytes); | |
for (Integer keyNum=0; keyNum < keysNeeded; keyNum++) { | |
prefs.putByteArray(keyNum.toString(), splitBytes[keyNum]); | |
} | |
} | |
private static byte[] get(Preferences prefs, String key) { | |
byte[] bytes = new byte[prefs.getInt("bytes", 1)]; | |
int bytesIndex = 0; | |
int keys = prefs.getInt("keys", 1); | |
for (Integer keyNum = 0; keyNum < keys; keyNum++) { | |
byte[] chunk = prefs.getByteArray(keyNum.toString(), null); | |
if (chunk == null) { | |
//new Exception("Chunk is null! Oh noes!").printStackTrace(); | |
continue; | |
} | |
for (int i=0; i<chunk.length && bytesIndex < bytes.length; i++) { | |
bytes[bytesIndex] = chunk[i]; | |
bytesIndex++; | |
} | |
} | |
return bytes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment