Reputation: 345
I'm trying to make an app that downloads a file from a server using SFTP. Whenever I run the debugger, everything seems to be fine with no errors. My log says that it has downloaded the specified file. However, I can't seem to find the file that was supposedly downloaded anywhere in my device. Any help?
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
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 java.util.List;
public class MainActivity extends Activity {
private String user = "user";
private String pass = "pass";
private String host = "hostname";
private int portNum = 22;
private String fileName = "sample.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<Void, Void, List<String>>() {
@Override
protected List<String> doInBackground(Void... params) {
try {
Downloader(fileName);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
public void Downloader(String fileName) {
JSch jsch = new JSch();
Session session = null;
String knownHostsDir = "/home/user/";
try {
jsch.setKnownHosts(knownHostsDir);
} catch (JSchException e) {
e.printStackTrace();
}
try {
session = jsch.getSession(user, host, portNum);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(pass);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.get(fileName);
Log.d(fileName, " has been downloaded");
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 3272
Reputation: 25448
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.get(fileName);
Log.d(fileName, " has been downloaded");
The single-argument version of ChannelSftp.get() doesn't write the remote file to a local file. It returns an InputStream. You're supposed to read the contents of the remote file from the InputStream, like this for example:
try (FileOutputStream out = new FileOutputStream("/some/file")) {
try (InputStream in = sftpChannel.get(fileName)) {
// read from in, write to out
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
}
}
Alternately, there are other versions of the get() method which will write the remote content to a local file for you.
Upvotes: 1