Created
March 21, 2015 01:39
-
-
Save thuytrinh/15fed89d10ead16c8e77 to your computer and use it in GitHub Desktop.
Write/read gzip stream properly
This file contains 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
import android.content.Context; | |
import android.test.InstrumentationTestCase; | |
import com.google.gson.Gson; | |
import com.google.gson.reflect.TypeToken; | |
import com.google.gson.stream.JsonReader; | |
import java.io.BufferedInputStream; | |
import java.io.BufferedOutputStream; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.io.OutputStreamWriter; | |
import java.util.zip.GZIPInputStream; | |
import java.util.zip.GZIPOutputStream; | |
import static org.assertj.core.api.Assertions.assertThat; | |
public class GzipTest extends InstrumentationTestCase { | |
public void testGzip() throws IOException { | |
final Context context = getInstrumentation().getTargetContext(); | |
final String[] expectedData = {"Awesome", "Cool", "Nice", "LGTM"}; | |
final String fileName = String.format("data_%d", System.nanoTime()); | |
{ | |
final File dataFile = new File(context.getFilesDir(), fileName); | |
final BufferedOutputStream outputStream = new BufferedOutputStream( | |
new GZIPOutputStream( | |
new FileOutputStream(dataFile) | |
)); | |
final Gson gson = new Gson(); | |
final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); | |
outputStreamWriter.write(gson.toJson(expectedData)); | |
outputStreamWriter.close(); | |
outputStream.close(); | |
} | |
{ | |
final File dataFile = new File(context.getFilesDir(), fileName); | |
final BufferedInputStream inputStream = new BufferedInputStream( | |
new GZIPInputStream( | |
new FileInputStream(dataFile) | |
)); | |
final InputStreamReader inputStreamReader = new InputStreamReader(inputStream); | |
final Gson gson = new Gson(); | |
final String[] data = gson.fromJson(new JsonReader(inputStreamReader), new TypeToken<String[]>() {}.getType()); | |
assertThat(data).isNotNull().hasSize(4); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment