2015-11-23 2 views
0

Я попытался прочитать txt-файл с буферизованным входным потоком и сжать его с помощью GZIP, он сработал. Однако, когда я пытаюсь извлечь сжатый файл с zip, файл кажется нечитаемым двоичным форматом, как я могу решить эту проблему? Ниже приведен мой код:сжать файл с помощью GZIP в java

public static void main(String[] args) { 
    compressWithGZIP(SAVE_PATH2, SAVE_PATH3); 
    //uncompressWithGZIP(SAVE_PATH3 + "compressed.gz", SAVE_PATH4); 
} 

private static void uncompressWithGZIP(String oripath, String outputPath) { 
    BufferedInputStream bi = null; 
    BufferedOutputStream bo = null; 
    try { 
     bi = new BufferedInputStream(new GZIPInputStream(
       new FileInputStream(oripath))); 
     bo = new BufferedOutputStream(new FileOutputStream(outputPath)); 
     int c; 
     while ((c = bi.read()) != -1) { 
      bo.write(c); 
     } 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (bi != null) { 
       bi.close(); 
      } 
      if (bo != null) { 
       bo.close(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 

     } 
    } 
} 

private static void compressWithGZIP(String filePath, String outputPath) { 
    if (outputPath == null || outputPath.isEmpty() 
      || !outputPath.endsWith(".gz")) { 
     outputPath += "compressed.gz"; 
    } 

    BufferedReader br = null; 
    BufferedOutputStream bo = null; 
    try { 
     br = new BufferedReader(new FileReader(filePath)); 
     bo = new BufferedOutputStream(new GZIPOutputStream(
       new FileOutputStream(outputPath))); 
     int c; 
     while ((c = br.read()) != -1) { 
      bo.write(c); 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      if (br != null) { 
       br.close(); 
      } 
      if (bo != null) { 
       bo.close(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 

     } 
    } 

} 

ответ

3

Классическая ошибка.

DO. НЕ. КОГДА-ЛИБО. ИСПОЛЬЗОВАНИЕ. А. ЧИТАТЕЛЬ. TO. ЧИТАТЬ. BINARY. ДАННЫЕ..

A Reader интерпретирует данные, считанные из файла как потенциальные символы, используя процесс декодирования символов. Там - - причина, по которой Java определяет как Reader, так и InputStream и Writer vs OutputStream.

Если вы имеете дело с двоичными данными, используйте InputStream и OutputStream. NEVER Читатель или писатель.

Другими словами, ваша проблема здесь:

br = new BufferedReader(new FileReader(filePath)); 
    bo = new BufferedOutputStream(new GZIPOutputStream(
      new FileOutputStream(outputPath))); 

Используйте InputStream, а не Reader, читать из исходного файла.