2015-07-11 226 views
0

我试图做一个应用程序,使用SFTP从服务器下载文件。每当我运行调试器时,一切似乎都没有错误。我的日志说它已经下载了指定的文件。但是,我似乎无法找到在我的设备中任何地方下载的文件。任何帮助?使用JSCH下载文件通过SFTP(android)

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(); 
     } 
    } 

} 

回答

0
ChannelSftp sftpChannel = (ChannelSftp) channel; 
sftpChannel.get(fileName); 
Log.d(fileName, " has been downloaded"); 

single-argument version of ChannelSftp.get()不写远程文件到本地文件。它返回一个InputStream。你应该阅读从InputStream远程文件的内容,像这样的例子:

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); 
     } 
    } 
} 

或者,有other versionsof theget() method这将写入远程内容到本地文件给你。