java编写创建json,将json数据转换成xml,ftp发送到服务器

news/2024/11/8 17:11:23/

一.项目简介

1.环境

1).jdk 1.6

2.jar包

commons-net-1.4.1.jar
gson-2.2.4.jar
jar 建议大家去官网上下载

3.项目结构

这里写图片描述

二.创建Json

1.javaBean

package kingdom.json;public class TransData 
{private String fq_name;    //交易发起人private String js_name;    //交易接收人private String hl_name;    //交易处理人private int money;         //交易金额private int pay_way;       //支付方式private String begin_time; //交易发起时间private String end_time;   //交易结束时间public String getFq_name() {return fq_name;}public void setFq_name(String fq_name) {this.fq_name = fq_name;}public String getJs_name() {return js_name;}public void setJs_name(String js_name) {this.js_name = js_name;}public String getHl_name() {return hl_name;}public void setHl_name(String hl_name){this.hl_name = hl_name;}public int getMoney() {return money;}public void setMoney(int money) {this.money = money;}public int getPay_way(){return pay_way;}public void setPay_way(int pay_way) {this.pay_way = pay_way;}public String getBegin_time() {return begin_time;}public void setBegin_time(String begin_time) {this.begin_time = begin_time;}public String getEnd_time() {return end_time;}public void setEnd_time(String end_time){this.end_time = end_time;}
}package kingdom.json;import java.util.List;public class DataGram 
{private String trans_code;   //交易代码private String trans_type;   //交易类型private String trans_name;   //交易名称private String jys_code;     //交易所代码private String jys_name;     //交易所名字private String jy_way;       //交易方式private List<TransData> ts_data;   //交易数据public String getTrans_code() {return trans_code;}public void setTrans_code(String trans_code) {this.trans_code = trans_code;}public String getTrans_type() {return trans_type;}public void setTrans_type(String trans_type) {this.trans_type = trans_type;}public String getTrans_name() {return trans_name;}public void setTrans_name(String trans_name) {this.trans_name = trans_name;}public String getJys_code() {return jys_code;}public void setJys_code(String jys_code) {this.jys_code = jys_code;}public String getJys_name() {return jys_name;}public void setJys_name(String jys_name) {this.jys_name = jys_name;}public String getJy_way() {return jy_way;}public void setJy_way(String jy_way) {this.jy_way = jy_way;}public List<TransData> getTs_data() {return ts_data;}public void setTs_data(List<TransData> ts_data) {this.ts_data = ts_data;}
}

2.创建Json

package kingdom.json;import java.util.List;
import java.util.ArrayList;import com.google.gson.Gson;public class CreatJson 
{public static String CreatTransJson(){String beanStr = null;DataGram dg = new DataGram();Gson gson = new Gson(); TransData td = new TransData();List<TransData> list = new ArrayList<TransData>();dg.setTrans_code("10016");dg.setTrans_type("转账");dg.setTrans_name("发行债券");dg.setJys_code("009");dg.setJys_name("北京金融交易所");dg.setJy_way("债券");dg.setTs_data(list);for(int i = 0; i < 3; ++i){td.setFq_name("小明");td.setJs_name("小王");td.setHl_name("小张");td.setMoney(100000 + i);td.setBegin_time("2017-03-09");td.setEnd_time("2017-09-22");list.add(td);}beanStr = gson.toJson(dg); return beanStr;}
}

3.json数据格式

{"trans_code":"10016","trans_type":"转账", "trans_name":"发行债券", "jys_code":"009", "jys_name":"北京金融交易所",  "jy_way":"债券",  "ts_data": [ { "fq_name":"小明", "js_name":"小王",  "hl_name":"小张"," money":100002,  "pay_way":0,  "begin_time":"2017-03-09",  "end_time":"2017-09-22"  } ,{"fq_name":"小明", "js_name":"小王",  "hl_name":"小张"," money":100002,  "pay_way":0,  "begin_time":"2017-03-09",  "end_time":"2017-09-22"  } ,{"fq_name":"小明", "js_name":"小王",  "hl_name":"小张"," money":100002,  "pay_way":0,  "begin_time":"2017-03-09",  "end_time":"2017-09-22"  }]
}

三.解析Json并创建XML

1.JavaBean代码

package kingdom.xml;import java.util.List;public class Result 
{private String trans_code;private String trans_type;private String trans_name;private String jys_code;private String jys_name;private String jy_way;private List<TranInfo> ts_data;public String getTrans_code() {return trans_code;}public void setTrans_code(String trans_code) {this.trans_code = trans_code;}public String getTrans_type(){return trans_type;}public void setTrans_type(String trans_type) {this.trans_type = trans_type;}public String getTrans_name() {return trans_name;}public void setTrans_name(String trans_name) {this.trans_name = trans_name;}public String getJys_code() {return jys_code;}public void setJys_code(String jys_code) {this.jys_code = jys_code;}public String getJys_name() {return jys_name;}public void setJys_name(String jys_name) {this.jys_name = jys_name;}public String getJy_way() {return jy_way;}public void setJy_way(String jy_way) {this.jy_way = jy_way;}public List<TranInfo> getTs_data(){return ts_data;}public void setTs_data(List<TranInfo> ts_data) {this.ts_data = ts_data;}public static class TranInfo {private String fq_name;private String js_name;private String hl_name;private int money;@Overridepublic String toString(){return "TranInfo [money=" + money + ", pay_way=" + pay_way + "]";}private int pay_way;private String begin_time;private String end_time;public String getFq_name() {return fq_name;}public void setFq_name(String fq_name) {this.fq_name = fq_name;}public String getJs_name() {return js_name;}public void setJs_name(String js_name) {this.js_name = js_name;}public String getHl_name() {return hl_name;}public void setHl_name(String hl_name) {this.hl_name = hl_name;}public int getMoney() {return money;}public void setMoney(int money) {this.money = money;}public int getPay_way() {return pay_way;}public void setPay_way(int pay_way) {this.pay_way = pay_way;}public String getBegin_time() {return begin_time;}public void setBegin_time(String begin_time) {this.begin_time = begin_time;}public String getEnd_time(){return end_time;}public void setEnd_time(String end_time){this.end_time = end_time;}}
}

2.解析Json并创建XML文件

package kingdom.xml;import kingdom.json.CreatJson;
import kingdom.xml.Result.TranInfo;import org.dom4j.*;
import org.dom4j.io.*;
import org.xml.sax.SAXException;import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.sun.xml.internal.bind.util.AttributesImpl;import java.lang.reflect.*;
import java.util.List;import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;public class XmlCreate 
{public static void creatXml() throws Exception{CreatJson cj = new CreatJson();String str =  cj.CreatTransJson();System.out.println(str);Gson gson = new Gson();Result result = gson.fromJson(str, Result.class);SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();try {  TransformerHandler handler = factory.newTransformerHandler();  Transformer transformer = handler.getTransformer();  transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");  transformer.setOutputProperty(OutputKeys.INDENT, "yes");    StreamResult ret = new StreamResult("./saxToxml.xml");  handler.setResult(ret);  AttributesImpl attr = new AttributesImpl();  handler.startDocument();  handler.startElement("", "", "root", attr);   attr.clear();  handler.startElement("", "", "trans_code", attr);  handler.characters(result.getTrans_code().toCharArray(), 0, result.getTrans_code().toCharArray().length);  handler.endElement("", "", "trans_code");  attr.clear();  handler.startElement("", "", "trans_type", attr);  handler.characters(result.getTrans_type().toCharArray(), 0, result.getTrans_type().toCharArray().length);  handler.endElement("", "", "trans_type");  attr.clear();  handler.startElement("", "", "jys_code", attr);  handler.characters(result.getJys_code().toCharArray(), 0, result.getJys_code().toCharArray().length);  handler.endElement("", "", "jys_code");  attr.clear();  handler.startElement("", "", "jy_way", attr);  handler.characters(result.getJy_way().toCharArray(), 0, result.getJy_way().toCharArray().length);  handler.endElement("", "", "jy_way");  attr.clear();List<TranInfo> ts_data =  result.getTs_data();for(int i = 0; i < ts_data.size(); ++i){handler.startElement("", "", "trans", attr);    attr.clear(); String m_mony = String.valueOf(ts_data.get(i).getMoney());handler.startElement("", "", "money", attr); handler.characters(m_mony.toCharArray(), 0, m_mony.toCharArray().length);  handler.endElement("", "", "money");  attr.clear();String pay_way = String.valueOf(ts_data.get(i).getPay_way());handler.startElement("", "", "pay_way", attr);  handler.characters(pay_way.toCharArray(), 0, pay_way.toCharArray().length);  handler.endElement("", "", "pay_way");  attr.clear();handler.startElement("", "", "begin_time", attr);  handler.characters(ts_data.get(i).getBegin_time().toCharArray(), 0, ts_data.get(i).getBegin_time().toCharArray().length);  handler.endElement("", "", "begin_time");  attr.clear();handler.endElement("", "", "trans");  }      handler.endElement("", "", "root");  handler.endDocument();  } catch (TransformerConfigurationException e) {  e.printStackTrace();  } catch (SAXException e) {  e.printStackTrace();  }}
}

2.XML文件数据

<?xml version="1.0" encoding="UTF-8"?>
<root><trans_code>10016</trans_code><trans_type>转账</trans_type><jys_code>009</jys_code><jy_way>债券</jy_way><trans><money>100002</money><pay_way>0</pay_way><begin_time>2017-03-092</begin_time></trans><trans><money>100002</money><pay_way>0</pay_way><begin_time>2017-03-092</begin_time></trans><trans><money>100002</money><pay_way>0</pay_way><begin_time>2017-03-092</begin_time></trans>
</root>

四.ftp发送到服务器

1.javaBean

package kingdom.ftp;public class Ftp 
{private String ipAddr;private Integer port;private String userName;private String pwd;private String path;public String getIpAddr() {return ipAddr;}public void setIpAddr(String ipAddr) {this.ipAddr = ipAddr;}public Integer getPort() {return port;}public void setPort(Integer port) {this.port = port;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public String getPath() {return path;}public void setPath(String path) {this.path = path;}
}

2.ftp代码

package kingdom.ftp;import java.io.InputStream;
import kingdom.json.CreatJson;
import kingdom.xml.XmlCreate;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;public class FtpClient 
{    private static FTPClient ftp;public static boolean connectFtp(Ftp f) throws Exception{ftp = new FTPClient();boolean flag=false;int reply;if(f.getPort()==null) {ftp.connect(f.getIpAddr(), 21);}else{ftp.connect(f.getIpAddr(), f.getPort());}boolean ok = ftp.login(f.getUserName(),  f.getPwd());if(ok == false){System.out.println("ftp服务器登录失败");return flag;}ok = ftp.setFileType(FTPClient.BINARY_FILE_TYPE);if(ok == false){System.out.println("设置文件类型失败");return flag;}reply = ftp.getReplyCode();      if (!FTPReply.isPositiveCompletion(reply)) {      ftp.disconnect();      return flag;      }      ftp.changeWorkingDirectory(f.getPath()); flag = true;      return flag;}public static void closeFtp(){if (ftp!=null && ftp.isConnected()) {try{ftp.logout();ftp.disconnect();} catch (IOException e) {e.printStackTrace();}}}public static void upload(File f) throws Exception{if (f.isDirectory()) {ftp.makeDirectory(f.getName());ftp.changeWorkingDirectory(f.getName());String[] files=f.list();for(String fstr : files){File file1 = new File(f.getPath()+"/"+fstr);if (file1.isDirectory()) {upload(file1);ftp.changeToParentDirectory();}else{File file2 = new File(f.getPath()+"/"+fstr);FileInputStream input = new FileInputStream(file2);ftp.storeFile(file2.getName(), input);input.close();}}}else{File file2=new File(f.getPath());FileInputStream input=new FileInputStream(file2);ftp.storeFile(file2.getName(), input);input.close();}}public static void startDown(Ftp f,String localBaseDir,String remoteBaseDir ) throws Exception{if (FtpClient.connectFtp(f)) {  try { FTPFile[] files = null; boolean changedir = ftp.changeWorkingDirectory(remoteBaseDir); if (changedir) { ftp.setControlEncoding("GBK"); files = ftp.listFiles(); for (int i = 0; i < files.length; i++) { try{ downloadFile(files[i], localBaseDir, remoteBaseDir); }catch(Exception e){ System.out.println("<"+files[i].getName()+">下载失败"); } } } } catch (Exception e) { System.out.println("下载过程中出现异常"); } }else{System.out.println("链接失败!");}}private  static void downloadFile(FTPFile ftpFile, String relativeLocalPath,String relativeRemotePath){ if (ftpFile.isFile()) {if (ftpFile.getName().indexOf("?") == -1) { OutputStream outputStream = null; try { File locaFile= new File(relativeLocalPath+ ftpFile.getName()); if(locaFile.exists()){ return; }else{ outputStream = new FileOutputStream(relativeLocalPath+ ftpFile.getName()); ftp.retrieveFile(ftpFile.getName(), outputStream); outputStream.flush(); outputStream.close(); } } catch (Exception e) { e.printStackTrace();} finally{ try { if (outputStream != null){ outputStream.close(); }} catch (IOException e) { System.out.println("输出文件流异常"); } } } } else { String newlocalRelatePath = relativeLocalPath + ftpFile.getName(); String newRemote = new String(relativeRemotePath+ ftpFile.getName().toString()); File fl = new File(newlocalRelatePath); if (!fl.exists()) { fl.mkdirs(); } try { newlocalRelatePath = newlocalRelatePath + '/'; newRemote = newRemote + "/"; String currentWorkDir = ftpFile.getName().toString(); boolean changedir = ftp.changeWorkingDirectory(currentWorkDir); if (changedir){ FTPFile[] files = null; files = ftp.listFiles(); for (int i = 0; i < files.length; i++) { downloadFile(files[i], newlocalRelatePath, newRemote); } } if (changedir){ftp.changeToParentDirectory(); } } catch (Exception e){ e.printStackTrace();} } } public static void main(String[] args) throws Exception{CreatJson cj = new CreatJson();System.out.println(cj.CreatTransJson());XmlCreate xmlc = new XmlCreate();xmlc.creatXml();Ftp f = new Ftp();f.setIpAddr("192.168.191.5");f.setUserName("guosj1");f.setPwd("123456");f.setPath("D:/iTudou");FtpClient.connectFtp(f);File file = new File("D:/Workplace/KindomFtpClient/saxToxml.xml");  FtpClient.upload(file);System.out.println("ok"); }  
}

关注问我技术公众号,加小问,拉您入技术交流群:
在这里插入图片描述


http://www.ppmy.cn/news/917790.html

相关文章

React Hooks 实用指南

为什么80%的码农都做不了架构师&#xff1f;>>> 前言 在React Conf 2018会议中&#xff0c;Dan Abramov 介绍了 React Hooks。官方的描述为 Hook是一项新功能提案&#xff0c;可让您在不编写类的情况下使用状态和其他React功能。 它们目前处于React v16.7.0-alpha中…

iPhone开发入门(10)— 设备上运行程序

博主&#xff1a;易飞扬原文链接 : http://www.yifeiyang.net/introduction-to-iphone-development-10-devices-running-the-program/转载请保留上面文字。 注册 iPhone Developer Program 启动程序的准备 连接Xcode 生成证明 创建和下载配置文件 注册证明书 设备注册 生成App …

GeoTrellis 尝试(springboot + swagger + spark + GeoTrellis)

原始使用springboot spark 整合在一起做了一个通过请求来驱动spark计算的demo工程&#xff0c;最近看了下GeoSpark,Geotrellis,GeoMeca关于GIS方面的大数据相关技术&#xff0c;就写了一个Demo,我这里用的是Spark 2.4.0 版本 scala 2.11 版本 Geotrellis 2.3.1版本 GeoTools 2…

批处理Bat教程-第八章:番外篇

转载自&#xff1a;http://docs.30c.org/dosbat/chapter08/ 8.1 批量十六进制二进制格式转换 想把数据(流)以十六进制或二进制的形式显示出来&#xff1f;UltraEdit之类的编辑软件一定是首选。即使是要自己亲自转出来&#xff0c;C/C等语言也会方便的多。如果您跟我一样选择使…

day5-os、sys模块

一.概述 开发运维相关支撑系统现今已成为Devops下的一大热门领域&#xff0c;Python在这方面也有着自己独到的优势。这类场景以及其他一些场景下&#xff0c;需要调用一些操作系统的接口&#xff0c;这就涉及到今天要讲述的OS模块和sys模块。 二.OS模块的常见用法 os.getcwd()获…

goudp文件传输服务器,golang实现ftp实时传输文件的案例

一、项目简介 本项目主要实现的功能是ftp客户端不断地将xml文件和jpg文件实时地上传到服务器,当然也可以是其他格式的文件。每当ftp客户端取到一个文件之后,将文件上传到服务器后,然后将其删除。 项目实现可配置,如果开发者有类似的需求,只需要修改配置文件就可以使用本项…

itudou(爱土豆) 免费官方版

itudou(爱土豆) 免费官方版 软件大小&#xff1a;29.1MB 软件语言&#xff1a;简体中文 软件授权&#xff1a;官方版 软件类别&#xff1a;下载工具 官方网站&#xff1a;www.33LC.com 应用平台&#xff1a;/WinXP/|Win7|/Vista/ itudou(爱土豆)是用以批量上传和下载土豆视频的…

总结hmdp项目中遇到的坑

目录 1、RedisTemplate执行lua脚本抛出异常java.lang.UnsupportedOperationException 原因 2、redis出现WRONGTYPE Operation against a key holding the wrong kind of value错误 原因 3、Hutool BeanToMap问题 1、RedisTemplate执行lua脚本抛出异常java.lang.Unsupporte…