Basically I have a text that is quite long, I need to compress it, store it in a file, and read it out later. here is what I did.
public static void outCompressNIO(String outFile, String src) {
FileChannel fc = null;
GZIPOutputStream gz = null;
try {
fc = new FileOutputStream(outFile).getChannel();
gz = new GZIPOutputStream(Channels.newOutputStream(fc));
gz.write(src.getBytes());
gz.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
gz.close();
fc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void inCompressNIO(String inFile) {
FileChannel fc = null;
GZIPInputStream gz = null;
try {
fc = new FileInputStream(inFile).getChannel();
gz = new GZIPInputStream(Channels.newInputStream(fc));
byte fileContent[] = new byte[1024];
StringBuilder sb = new StringBuilder();
while ((gz.read(fileContent)) != -1) {
sb.append(new String(fileContent));
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
gz.close();
fc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
But the string I got back from the compressed file is different with the original one from place to place. Anyone knows why? By the way, my main goal is that I need to effectively compress a long string(around 15M) into a file, and decompress it into main memory on android. I tried to just use Object IO in java to achieve this, it is achieved with no problem on my pc. But on android, if the string object is more than 3M, it takes forever to cast the object I got from ObjectInputStream to String. So I am trying other ways to avoi开发者_StackOverflow中文版d casting. The above is one of my attempts, but since I know little about NIO, I am probably doing it all wrong, so anyone knows a more efficient way to achieve this, please point me to the right direction, Thanks a lot.
- Throw away the FileChannel and just use FileInputStream. You're using java.io here really, not NIO, except when you get the channel, so you're just doing it the hard way.
- Specify a charset name to String.getBytes().
- Store the result of read(byte[]) into a variable. Use that variable when appending to sb, i.e. sb.append(new String(buffer,0,count, charset));
- Better still, wrap an InputStreamReader around the GZipInputStream, constructed with the same charset name, read into a char[] array, not a byte[] array, and use sb.append(charBuffer, 0, count). This avoids the assumption you're presently making that the bytes you read constitute an entire String.
精彩评论