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();
}
}
- 上传代码部分 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();
}
}