老实说,这不应该有这么多问题,但我一定错过了一些明显的东西。
我可以使用GZIPOutputStream
很好地压缩文件,但是当我尝试直接获取输入(不是从文件,而是从管道或其他东西)时,我去对我的文件调用gunzip -d以查看它是否正确解压,它告诉我它立即进入文件末尾。基本上,我希望这些能够发挥作用
echo foo | java Jgzip >foo.gz
或
java Jzip <test.txt >test.gz
并且不能保证这些是字符串,因此我们正在逐字节读取。我以为我可以只使用 System.in 和 System.out,但这似乎不起作用。
public static void main (String[] args) {
try{
BufferedInputStream bf = new BufferedInputStream(System.in);
byte[] buff = new byte[1024];
int bytesRead = 0;
GZIPOutputStream gout = new GZIPOutputStream (System.out);
while ((bytesRead = bf.read(buff)) != -1) {
gout.write(buff,0,bytesRead);
}
}
catch (IOException ioe) {
System.out.println("IO error.");
System.exit(-1);
}
catch (Throwable e) {
System.out.println("Unexpected exception or error.");
System.exit(-1);
}
}
最佳答案
我建议:
OutputStream gout= new GZIPOutputStream( System.out );
System.setOut( new PrintStream( gout )); //<<<<< EDIT here
while(( bytesRead = bf.read( buff )) != -1 ) {
gout.write(buff,0,bytesRead);
}
gout.close(); // close flush the last remaining bytes in the buffer stream
关于java - 压缩输入流 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13098380/