-2

我在java中有一张地图(1.7版)

public void doTest() {
    try {
         Map<String, String> data = new HashMap<String, String>();
         data.put("Product", "someProduct");
         data.put("CreatedOn", "Fri May 08 02:25:03 IST 2015");
         data.put("Module", "someService");
         data.put("Type", "ERROR");
         data.put("Message", "LogId:635666739033286524 Message:WSClient.FetchReservation::WS FetchReservation calledSystem.Net.WebException: The operation has timed out at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) at .BOTWSClient.ChannelDirectWS.YieldGain.fFetchReservation(String strReservationXML) at BOTWSClient.WSClient.FetchReservation(String RequestXML) ");
         data.put("IP", "");
         data.put("Name", "WriteLog");

         byte[] byteArray = convert(data);
         int response = port.writelogcollection(byteArray);

    } catch(Exception e) {
        e.printStackTrace();
    }
}

  public byte[] convert(Map obj) throws IOException {
   ObjectOutputStream os = null;

  ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
  os = new ObjectOutputStream(new GZIPOutputStream(byteStream));
  os.writeObject(obj);
  os.flush();
  byte[] sendBuf = byteStream.toByteArray();
  os.close();
 return sendBuf;

}

 public static String writelogcollection(byte[] bytes) throws IOException {
BufferedReader bf;
    String outStr;
    try (GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes))) {
        bf = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
        outStr = "";
        String line;
        while ((line = bf.readLine()) != null) {
            outStr += line;
        }
    }
    bf.close();
    return outStr;
}

我正在尝试 GZIPInputStream 但得到以下异常

Exception occurred in target VM: Not in GZIP format 
    java.util.zip.ZipException: Not in GZIP format
    at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:164)
    at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:78)
    at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:90)

我确定它不是 java 版本问题,我在代码中缺少它。

4

1 回答 1

1

你的错误在这里:

os.flush();
byte[] sendBuf = byteStream.toByteArray();
os.close();

它应该是

os.flush();
os.close();
byte[] sendBuf = byteStream.toByteArray();

因为 whileflush()只写入到目前为止已经写入的数据,而且close()还写入了一些重要的元数据,这些元数据是正确形成 gzipped 对象流所需的。

您的代码也存在不同的小问题,例如writelogcollection应该是writeLogCollection,您应该使用 try-with-resources 关闭您的BufferedReaderand InputStreamReader(您根本不关闭),以及其他代码清洁问题。保持代码干净可以让你更容易理解问题所在。

哦,最后但并非最不重要的一点是,首先使用 编写对象ObjectOutputStream然后使用BufferedReader. ObjectOutputStream如果您尝试将其解释为文本,则会生成二进制数据,这些数据将变成垃圾。

于 2015-05-09T11:48:15.763 回答