一、GZIP解析内容
简述:通过一个网络地址,下载到一个.gz格式的压缩包,然后解压获取里面的文本文件,再将文本文件中的JSON串(仅只有字符串,格式统一),数据入库。当时听到这个要求的时候感觉…好恐怖,听着就很复杂,不可能写的出来,后来发现就几行代码,不得不说IO流厉害。
1.通过地址获取url对象
URL url = new URL(path);
2.打开HTTP链接
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
3.设置请求参数
conn.setRequestMethod("GET");
//设置连接超时时间
conn.setConnectTimeout(5 * 1000);
4.从链接获得输入流(字节流)
InputStream inStream = conn.getInputStream();
5.获得GZIP输入流
GZIPInputStream gzin = new GZIPInputStream(inStream);
6.获得读入流
BufferedReader br = new BufferedReader(new InputStreamReader(gzin));
7.逐行拼接成字符串
StringBuffer sb = new StringBuffer();
String s = "";
while((s = br.readLine())!=null){
sb.append(s);
}
8.JSON转Model
Model model= JSON.parseObject(sb.toString(), Model.class);
二、String和XmL和流的转换
1.从String得到XML然后解析
String str = “”;
Document document = DocumentHelper.parseText(sb.toString());
//获取根元素
Element rootElement = document.getRootElement();
Map map = new HashMap();
//一层一层获得根元素的所有子节点
for(Iterator it = rootElement.elementIterator();it.hasNext();){
Element node = (Element) it.next();
for(Iterator it2 = node.elementIterator();it2.hasNext();){
Element nodeNode = (Element) it2.next();
map.put(nodeNode.getName(),nodeNode.getText());
}
}
2.从网络地址得到XML
String string = "";
URL url = new URL(string);
//获得链接
HttpURLConnection connection = url.openConnection();
//获得输入流
InputStream inputStream1 = connection.getInputStream();
//获得读入流
SAXReader saxReader = new SAXReader();
Document document1 = saxReader.read(inputStream);
//获取根元素
Element rootElement = document.getRootElement();
Map map = new HashMap();
//一层一层获得根元素的所有子节点
for(Iterator it = rootElement.elementIterator();it.hasNext();){
Element node = (Element) it.next();
for(Iterator it2 = node.elementIterator();it2.hasNext();){
Element nodeNode = (Element) it2.next();
map.put(nodeNode.getName(),nodeNode.getText());
}
}
三、结束语
IO在上课的时候学习,但是很长时间没有使用,基本也没有什么知识留下了,这种写法可能不是很严谨,因为记得流的关闭和异常捕捉对程序的运行很重要。对文件的处理,一般都会想到流的操作,记得还有字节流,字符流,数据流,管道流什么…需要学习的东西还很多啊