Skip to content

Instantly share code, notes, and snippets.

@dimkir
Created November 22, 2013 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimkir/7599874 to your computer and use it in GitHub Desktop.
Save dimkir/7599874 to your computer and use it in GitHub Desktop.
Processing sketch : saveBytesGZFailure
public void saveBytesZZZ(String filename, byte[] data) {
saveBytesZZZ(saveFile(filename), data);
}
/**
* @nowebref
* Saves bytes to a specific File location specified by the user.
*/
public void saveBytesZZZ(File file, byte[] data) {
println("saveBytes(File): " + file.getAbsolutePath() );
File tempFile = null;
try {
File parentDir = file.getParentFile();
tempFile = File.createTempFile(file.getName(), makeTempFileExtensionFromOriginal(file) , parentDir);
println("saveBytes(File): temp file: " + tempFile.getAbsolutePath() );
OutputStream output = createOutput(tempFile);
saveBytes(output, data);
output.close();
output = null;
if (file.exists()) {
if (!file.delete()) {
System.err.println("Could not replace " + file.getAbsolutePath());
}
}
if (!tempFile.renameTo(file)) {
System.err.println("Could not rename temporary file " +
tempFile.getAbsolutePath());
}
} catch (IOException e) {
System.err.println("error saving bytes to " + file);
if (tempFile != null) {
tempFile.delete();
}
e.printStackTrace();
}
}
/**
* Makes extension for the tmp file, based on the name of the original file.
* @return NULL in case NO ".gz" extension is necessary, and ".gz" if original file has it.
*/
private static String makeTempFileExtensionFromOriginal(File originalFile){
if ( originalFile.getAbsolutePath().toLowerCase().endsWith(".gz") ){
return ".gz";
}
else{
return null;
}
}
//#GIST:7599874
final int C_STRING_COUNT = 10 * 1000;
void setup() {
//Utils.sketchPath = sketchPath("");
String[] strings = new String[C_STRING_COUNT];
for (int i = 0 ; i < C_STRING_COUNT ; i++) {
strings[i] = new String("Number " + i );
}
saveStrings("regular_file.txt", strings);
saveStrings("gzipped_file.txt.gz", strings);
// the compression would work also with saveBytes("my_byte_file.bin.gz", someByteArray);
// and now let's load gzipped file back
String[] comingBackFromGzipped = loadStrings("gzipped_file.txt.gz");
println("Loaded back from gzipped: " + comingBackFromGzipped.length + " strings");
println("Here's sample 10 items, to show that they were loaded back fine:" );
for (int i = 0; i < 10; i++) {
println(comingBackFromGzipped[i]);
}
// Test by gyula
byte b[] = loadBytes("gzipped_file.txt.gz");
saveBytesZZZ("regular_file.txt.bin", b);
saveBytesZZZ("gzipped_file.txt.bin.gz", b);
exit();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment