栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 实现将对象保存到文件,并将文件压缩成zip包

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 实现将对象保存到文件,并将文件压缩成zip包

// 需要引入 org.apache.ant 包

  public static void main(String[] args) throws IOException {

    String text = "{n" +
        "  "regions": [n" +
        "    {n" +
        "      "name": "string",n" +
        "      "referenceNo": "string",n" +
        "      "warehouses": [n" +
        "        {n" +
        "          "address": "string",n" +
        "          "coordiante": {n" +
        "            "coordsys": "string",n" +
        "            "latitude": 0,n" +
        "            "longitude": 0n" +
        "          },n" +
        "          "name": "string",n" +
        "          "referenceNo": "string"n" +
        "        }n" +
        "      ]n" +
        "    }n" +
        "  ]n" +
        "}";

    File file = File.createTempFile("file", ".txt");
    FileOutputStream fop = new FileOutputStream(file);
    if (!file.exists()) {
      file.createNewFile();
    }

    // get the content in bytes
    byte[] contentInBytes = text.getBytes();
    fop.write(contentInBytes);
    fop.flush();
    fop.close();

    final File test = listToZip(Lists.newArrayList(file), "test");
    System.out.println(test.getPath());
  }

  public static File listToZip(List list, String zipfilename) {
    FileInputStream is = null;
    File f = null;
    ZipOutputStream zos = null;
    try {
      if (list != null && list.size() > 0) {
        // String uri = GlobalConfig.getConfigValue("zipFile.path");
        f = File.createTempFile(zipfilename, ".zip");
        if (!f.exists()) {
          f.mkdirs();
        }
        // 创建zip文件输出流
        zos = new ZipOutputStream(new FileOutputStream(f));
        zos.setEncoding("GBK");
        for (int i = 0; i < list.size(); i++) {
          File file = list.get(i);
          if (file.exists()) {
            // 创建源文件输入流
            is = new FileInputStream(file);
            zos.putNextEntry(new ZipEntry(file.getName()));
            byte[] buf = new byte[2048];
            int length = -1;
            while ((length = is.read(buf)) != -1) {
              zos.write(buf, 0, length);
              zos.flush();
            }
            zos.closeEntry();
            is.close();
          } else {
            System.out.println("源文件不存在");
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (is != null) {
          is.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        if (zos != null) {
          zos.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return f;
  }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/424604.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号