使用DEFLATE压缩算法压缩后,Base64编码的方式传输经压缩编码的文件内容

 1、先把文件以流的方式InputStream读入in.read(s, 0, in.available());

/**
	 * 功能:将批量文件内容使用DEFLATE压缩算法压缩,Base64编码生成字符串并返回<br>
	 * 适用到的交易:批量代付,批量代收,批量退货<br>
	 * @param filePath 批量文件-全路径文件名<br>
	 * @return
	 */
	public static String enCodeFileContent(String filePath,String encoding){
		String baseFileContent = "";
		
		File file = new File(filePath);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			int fl = in.available();
			if (null != in) {
				byte[] s = new byte[fl];
				in.read(s, 0, fl);
				// 压缩编码
                //TODO
				baseFileContent = 
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		return baseFileContent;
	}

2、进行BASE64编码

Base64.encodeBase64(inputByte);

3、对byte[]进行压缩 deflater方法

/**
	 * 压缩.
	 * 
	 * @param inputByte 需要解压缩的byte[]数组
	 * @return 压缩后的数据
	 * @throws IOException
	 */
	public static byte[] deflater(final byte[] inputByte) throws IOException {
		int compressedDataLength = 0;
		Deflater compresser = new Deflater();
		compresser.setInput(inputByte);
		compresser.finish();
		ByteArrayOutputStream o = new ByteArrayOutputStream(inputByte.length);
		byte[] result = new byte[1024];
		try {
			while (!compresser.finished()) {
				compressedDataLength = compresser.deflate(result);
				o.write(result, 0, compressedDataLength);
			}
		} finally {
			o.close();
		}
		compresser.end();
		return o.toByteArray();
	}

 综上:

baseFileContent = new String(Base64.encodeBase64(Util.deflater(s)),encoding);

猜你喜欢

转载自blog.csdn.net/jellyjiao2008/article/details/84325885
今日推荐