因为测试流程中,所测客户端会根据服务器A返回的response决定发送给服务器B的请求里各参数的值,所以现在需要模拟服务器的响应。而这个项目服务器A的响应式返回一个流,一个GZIP压缩格式流,压缩的是多个文件,所以需要编写相应的groovy脚本。我这里使用了apache的ant包。不过在运行的时候出错了。错误提示如下
Caught: java.io.IOException: request to write ‘1024‘ bytes exceeds size in header of ‘29886‘ bytes for entry ‘rate.csv‘
java.io.IOException: request to write ‘1024‘ bytes exceeds size in header of ‘29886‘ bytes for entry ‘rate.csv‘
	at org.apache.tools.tar.TarOutputStream.write(TarOutputStream.java:279)
	at org.apache.tools.tar.TarOutputStream.write(TarOutputStream.java:260)
	at org.apache.tools.tar.TarOutputStream$write.call(Unknown Source)
	at temp.packFile(temp.groovy:26)
	at temp.process(temp.groovy:51)
	at temp.run(temp.groovy:55)。
按照字面意思,然后仔细看了下api文档read(byte[] b), read(byte[] b,int off, int len), write(byte[] wBuf), write(byte[] wBuf, int wOffset, int numToWrite)的相关解释后, 经过尝试,终于解决了。看来我以前读取文件和写入文件使用一个参数的方法的习惯不好,虽然之前都没有出问题,但是这次就出现了,以后还是使用read(byte[] b,int off, int len)和write(byte[] wBuf, int wOffset, int numToWrite),这样就能避免这个错误的再次发生了。
附上代码
import java.util.zip.GZIPOutputStream
import org.apache.tools.tar.TarEntry
import org.apache.tools.tar.TarOutputStream
 public void packFile(String... filePath){
	 int num=filePath.length;
	 String targetPath=filePath[num-1]
	 BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(targetPath));
	 TarOutputStream tos=new TarOutputStream(bos);
	 tos.setLongFileMode(TarOutputStream.LONGFILE_GNU);
	 for(int i=0;i<num-1;i++){
		 File sourceFile=new File(filePath[i]);
		 TarEntry te=new TarEntry(sourceFile.getName());
		 te.setSize(sourceFile.length());
		 println(sourceFile.length())
		 tos.putNextEntry(te);	 
		 byte[] buffer=new byte[1024];
		 BufferedInputStream bis=new BufferedInputStream(new FileInputStream(sourceFile));
		 int count=0
while((count=bis.read(buffer,0,1024))>-1){
			 tos.write(buffer,0,count);     
		 } 
		 tos.closeEntry();
		 tos.flush();
		 bis.close();
	 }
	 tos.close();
 }
 
 public void compressFile(String filePath){
	 FileInputStream fis=new FileInputStream(filePath);
	 GZIPOutputStream gos=new GZIPOutputStream(new FileOutputStream(filePath+".gz"));
	 byte[] buffer=new byte[1024];
	 while(fis.read(buffer)>-1){
		 gos.write(buffer);
	 }
	 fis.close();
	 gos.finish();
	 gos.close();
 }
 
public void process() {
	String sourcePath1="D:/rate.csv";
	String sourcePath2="D:/plan.csv";
	String tarPath="D:/test/test.tar";
	packFile(sourcePath1,sourcePath2,tarPath);
	compressFile(tarPath);
 }
process();
使用TarOutputStream出现 request to write '1024' bytes exceeds size in header错误的解决方法
原文:http://www.cnblogs.com/jefzha/p/5398355.html