我使用GZIPOutputStream或ZIPOutputStream压缩一个String(我string.length()的小于20),但压缩结果比原始字符串长.
在某些网站上,我发现有些朋友说这是因为我原来的字符串太短,GZIPOutputStream可以用来压缩更长的字符串.
那么,有人可以给我一个压缩字符串的帮助吗?
我的功能如下:
String compress(String original) throws Exception {
}
Run Code Online (Sandbox Code Playgroud)
更新:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import java.util.zip.*;
//ZipUtil
public class ZipUtil {
public static String compress(String str) {
if (str == null || str.length() == 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
return out.toString("ISO-8859-1");
}
public static void main(String[] args) throws IOException {
String string = "admin";
System.out.println("after compress:"); …Run Code Online (Sandbox Code Playgroud) public static String compressString(String str) throws IOException{
if (str == null || str.length() == 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
Gdx.files.local("gziptest.gzip").writeString(out.toString(), false);
return out.toString();
}
Run Code Online (Sandbox Code Playgroud)
当我将该字符串保存到文件并gunzip -d file.txt在unix中运行时,它会抱怨:
gzip: gzip.gz: not in gzip format
Run Code Online (Sandbox Code Playgroud) 我有一个Object为
private String name;
private int age;
private String country;
// getters and setters
Run Code Online (Sandbox Code Playgroud)
和功能是
protected void write(@Nonnull final Document document, @Nonnull final OutputStream stream) throws PersistenceException {
try {
jaxbContext.createMarshaller().marshal(document, stream);
} catch (final JAXBException e) {
LOGGER.error(e.getMessage(), e);
throw new PersistenceException("Failed to marshall document " + docment.getUniqueId() + ": " + e.getMessage(), e);
}
}
Run Code Online (Sandbox Code Playgroud)
我把它转换成zip文件为
ByteArrayOutputStream stream = new ByteArrayOutputStream();
write(document, stream);
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(new FileOutputStream(new File(getOutputFilePath(document.getUniqueId()))));
gzipOutputStream.write(stream.toByteArray());
Run Code Online (Sandbox Code Playgroud)
这会创建zip文件,但当我尝试打开它时,它会说
gzip: document.xml.gz: …Run Code Online (Sandbox Code Playgroud)