Based on user input data and database data, i need to create a file and place it in remote machine. So the better way i could think of was connect to remote machine and write the file directly there. So far using JSch
i connected to remote machine. but i have no idea how to write a file in a particular location (root/usr/path/)
in this path i need to write and place a file (ddr12213124.NEW or ddr12213124.CSV)
.
I have attached the code for connecting to remote machine
package com.trial.classes;
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.UserInfo;
public class transferFile {
public static void main(String[] args) {
// TODO Auto-generated method stub
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("ragesh", "10.0.0.1", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("password");
session.connect();
System.out.println("Connected to session successfully");
Channel channel = session.openChannel("sftp");
channel.connect();
System.out.println("Connected to Channel successfully");
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
}
}
}
Now i would like to create a file (ddr12213124.NEW or ddr12213124.CSV)
and place it in the path root/usr/path/
I asked this question earlier but it was marked duplicate and i was asked to raise a new question. This is not duplicate. No appropriate answer was found so far in the link that was posted earlier.
You can use ChannelSFTP#put method to write a file to remote directory. there are several flavors of the put method and you can use any one as per your needs. Here is a sample code to write a File from Local System to remote system:
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("ragesh", "10.0.0.1", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("password");
session.connect();
System.out.println("Connected to session successfully");
Channel channel = session.openChannel("sftp");
channel.connect();
System.out.println("Connected to Channel successfully");
ChannelSftp sftpChannel = (ChannelSftp) channel;
// this will read file with the name test.txt and write to remote directory
sftpChannel.cd("/root/usr/path");
File f = new File("test.txt");
sftpChannel.put(new FileInputStream(f), f.getName()); // here you can also change the target file name by replacing f.getName() with your choice of name
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.