JAVA JSch,从数据库查出来数据,将其转为CSV,并将CSV文件使用SFTP上传到远程LINUX服务器的固定目录下

5 篇文章 0 订阅
2 篇文章 0 订阅
本文介绍了如何使用Java从数据库查询数据并转换为CSV文件,随后通过SSH连接将文件上传至目标服务器的过程。涉及的技术包括JDBC、QueryRunner、CSV文件操作和JSch库进行远程文件上传。
摘要由CSDN通过智能技术生成

1.从DB查出来数据,并将其存入内存中:
QueryRunner queryRunner = new QueryRunner();
String sql2 = “select * from table2”;
List<Object[]> result = queryRunner.query(conn.getConnsource(),sql2,new ArrayListHandler());

2.根据从数据库查出来的LIST<object[]>对象,将其转为CSV文件:

public File  exportCsv(List<Object[]> list,String fileName) throws IOException, IllegalArgumentException, IllegalAccessException{
    File file = new File("d:\\fileName");
    //构建输出流,同时指定编码
    OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
    //csv文件是逗号分隔,除第一个外,每次写入一个单元格数据后需要输入逗号

// for(String title : titles){
// ow.write(title);
// ow.write(",");
// }
//以上部分是写头文件
//写完文件头后换行
// ow.write("\r\n");
//写内容
for(Object[] obj : list){
//利用反射获取所有字段
for(int i = 0; i < obj.length ; i++){
//设置字段可见性
if(null != obj[i]){
ow.write(obj[i].toString());
}else {
}
ow.write("|");
continue;
}
//写完一行换行
ow.write("\r\n");
}
ow.flush();
ow.close();
return file;
}

2.登录对应的服务器,并上传文件
public void upLoadToTargetServer(File file) throws JSchException {
    String dPath="/usr/demo/";
    JSch jsch = new JSch();
    Session session = null;
    try {
        //用户名、ip地址、端口号
        session = jsch.getSession("账号", "服务器IP", 22);
    } catch (JSchException e) {
        e.printStackTrace();
    }
    // 设置登陆主机的密码
    session.setPassword("密码");// 设置密码
    // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
    session.setConfig("StrictHostKeyChecking", "no");
    // 设置登陆超时时间
    try {
        session.connect(20000);
    } catch (JSchException e) {
        e.printStackTrace();
    }
    Channel channel = null;
    try {
        channel = (Channel) session.openChannel("sftp");
        channel.connect(8000000);
        ChannelSftp sftp = (ChannelSftp) channel;
        String lastPath =  "";
        try {
            sftp.cd(dPath+lastPath);
            upload( dPath ,file ,sftp);
        } catch (SftpException e) {
            sftp.mkdir(dPath+lastPath);
            sftp.cd(dPath+lastPath);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        session.disconnect();
        channel.disconnect();
    }
}
  1. 上传代码部分 public void upload(String directory, File file, ChannelSftp sftp) {
    try {
    sftp.cd(directory);
    // File file = new File(uploadFile);
    sftp.put(new FileInputStream(file), file.getName());
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值