在Java中将csv文件写入gzip

时间:2018-08-13 10:11:01

标签: java csv gzip

如何在Java中将csv文件写入gzip。在编写我的csv类型时,将其更改为文件类型。我希望它是.csv ??? 这是我使用的代码...

public class zipWrite extends commonParts{

    public static void zip() throws Exception{

        zipWriter=  new FileOutputStream("C:\\Users\\myzip.gz");
        outputStream = new GZIPOutputStream(zipWriter);
        zipIn = new FileInputStream("C:\\Users\\mycsv.csv");
        byte []buffer = new byte[1024];
        int length;
        while ((length = zipIn.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
        zipIn.close();              
        outputStream.close();
        } 

}

1 个答案:

答案 0 :(得分:0)

如果您表示输出Gzip文件中包含的CSV文件不保留CSV扩展名,则解决方案是将输出文件名定义为“ myzip.csv.zip”:

  private static final String INPUT_FILE = "C:\\Users\\mycsv.csv";
  private static final String OUTPUT_FILE = "C:\\Users\\myzip.csv.gz";

  public static void zip() throws IOException {
    byte[] buffer = new byte[2048];
    FileInputStream inputStream = new FileInputStream(INPUT_FILE);
    FileOutputStream outputStream = new FileOutputStream(OUTPUT_FILE);
    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
    int length;
    while ((length = inputStream.read(buffer)) > 0) {
      gzipOutputStream.write(buffer, 0, length);
    }
    inputStream.close();
    gzipOutputStream.close();
  }

gzip中的文件将包含“ myzip.csv”文件。