服务端获取通过http post方式传的经过zip压缩后的数据,需求是对数据处理后,写入log4j.
步骤:
1、获取数据流;
2、数据写入中间文件;
3、不解压生成文件,直接读取数据;
4、对数据处理后写入log4j。
//controller类
import com.baomihua.utils.Commons;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
@Controller
public class apptest {
@RequestMapping(value="/t",method= RequestMethod.POST)
public void app(HttpServletRequest req, HttpServletResponse rep) throws Exception{
//临时文件在服务器目录(appdata为文件名)
String file = "/usr/local/tomcat/apache-tomcat-7.0.93/appdata";
//获取数据流
ServletInputStream inputStream = req.getInputStream();
//调用方法,将数据流写入临时文件
Commons.writeToLocal(file,inputStream);
//对临时文件数据解压
ZipFile zf = new ZipFile(file);
InputStream in = new BufferedInputStream(new FileInputStream(file));
ZipInputStream zin = new ZipInputStream(in);
ZipEntry ze;
while ((ze = zin.getNextEntry()) != null) {
if (ze.isDirectory()) {
} else {
long size = ze.getSize();
if (size > 0) {
BufferedReader br = new BufferedReader(
new InputStreamReader(zf.getInputStream(ze)));
String line;
while ((line = br.readLine()) != null) {
//调用方法对解压后的数据处理,并写入log4j
writeData.appData(req,rep,line);
}
br.close();
}
}
}
zin.closeEntry();
}
}
写入本地文件方法
/**
* 将InputStream写入本地文件
* @param destination 写入本地目录
* @param input 输入流
* @throws IOException IOException
*/
public static void writeToLocal(String destination, InputStream input)
throws IOException {
int index;
byte[] bytes = new byte[1024];
FileOutputStream downloadFile = new FileOutputStream(destination);
while ((index = input.read(bytes)) != -1) {
downloadFile.write(bytes, 0, index);
downloadFile.flush();
}
input.close();
downloadFile.close();
}
简单处理数据后,将数据写入log4j
public class writeData {
private static final Log logger = LogFactory.getLog("logger");
public static void appData(HttpServletRequest req, HttpServletResponse rep,String str)throws Exception{
List<String> logList = new ArrayList<String>();
...(数据处理过程)
StringBuffer line = new StringBuffer();
Boolean isfirst = Boolean.valueOf(true);
Iterator<String> it = logList.iterator();
while (it.hasNext()) {
if (isfirst.booleanValue())
isfirst = Boolean.valueOf(false);
else
line.append("\001");
line.append((String) it.next());
}
logger.info(line.toString().replace("\n", "").replace("\r", ""));
}
}