0
我想使用Deflater类来编码一个文本文件。难点是我不想编码整个文本文件,而只是每行的一个子串。我的文本文件看起来是这样的:错误在几个输入上使用deflater
元件(1):{dataToEncode}
元件(2):{dataToEncode}
我想返回一个HashMap,其中关键是元素ID(整数)和值是与括号中的行部分对应的压缩字节。我想为所有行使用相同的字典(不是预设),因为它们的内容非常接近。此外,最终,该算法将不得不在流上工作,即新行将被写入输入文本文件中并且应该在它们被添加后被压缩。
我,如果我重置deflater但我认为这也将重置编码每行后的字典,这是不一样保持相同的词典一直以来的元素注释是不太一样有效可用的版本。
public static HashMap< Integer, byte[]> encoding(String textfile) throws FileNotFoundException, UnsupportedEncodingException {
HashMap< Integer, byte[]> elements = new HashMap< Integer, byte[]>();
Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION);
File file = new File(textfile + ".txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String toCompress = sc.nextLine();
if (toCompress.substring(0, 7).equals("ELEMENT")) {
String infoToCompress = toCompress.substring(toCompress.indexOf('{') + 1, toCompress.indexOf('}'));
byte [] input = infoToCompress.getBytes("UTF-8");
byte [] output = new byte[input.length + 100];
compresser.setInput(input);
compresser.finish();
int compressedDataLength = compresser.deflate(output);
Integer element = Integer.parseInt(toCompress.substring(toCompress.indexOf('(')+1, toCompress.indexOf(")")));
elements.put(element, output);;
compresser.reset();
}
}
compresser.end();
sc.close();
return elements;
}
如果我不使用compresser.reset(),只有第一个元件被压缩,然后将其编译,但没有预期的结果。谢谢你的帮助。