Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用onClick从远程服务器下载SFTP_Java_Android_Sftp_Jsch - Fatal编程技术网

Java 使用onClick从远程服务器下载SFTP

Java 使用onClick从远程服务器下载SFTP,java,android,sftp,jsch,Java,Android,Sftp,Jsch,我目前正在开发一个应用程序,它可以打印远程服务器目录中的文件列表,并可以单击指定的文件进行下载 到目前为止,这就是我所拥有的: public class MainActivity extends Activity { private String user = "username"; private String pass = "password"; private String host = "hostname"; private int portNum =

我目前正在开发一个应用程序,它可以打印远程服务器目录中的文件列表,并可以单击指定的文件进行下载

到目前为止,这就是我所拥有的:

public class MainActivity extends Activity {


    private String user = "username";
    private String pass = "password";
    private String host = "hostname";
    private int portNum = 22;

    private static final String SFTPWORKINGDIR = "/path/to/file";
    private String fileName;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ListView list = (ListView)findViewById(R.id.choose_sound_listView);

        new AsyncTask<Void, Void, List<String>>() {
            @Override
            protected List<String> doInBackground(Void... params) {
                try {
                    return executeRemoteCommand(user, pass, host, portNum);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            public void onPostExecute(List<String> soundNames){
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_expandable_list_item_1, android.R.id.text1, soundNames);
                list.setAdapter(adapter);

                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int position, long arg3) {

                        String  newFileName = (String) list.getItemAtPosition(position);

                        fileName = newFileName;

                        Downloader(fileName);

                        // Show Alert
                        Toast.makeText(getApplicationContext(),
                                "Downloaded " + fileName , Toast.LENGTH_LONG).show();
                    }
                });
            }
        }.execute();
    }

    public List<String> executeRemoteCommand(String username, String password, String hostname, int port) throws Exception {

        List<String> soundNames = new ArrayList<String>();

        JSch jsch = new JSch();
        Session session = jsch.getSession(username, hostname, port);
        session.setPassword(password);

        // Avoid asking for key confirmation
        Properties prop = new Properties();
        prop.put("StrictHostKeyChecking", "no");
        session.setConfig(prop);

        session.connect();

        String command = "ls -la | awk '{ print $9}'";

        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);

        ((ChannelExec) channel).setErrStream(System.err);

        InputStream in = channel.getInputStream();

        System.out.println("Connect to session...");
        channel.connect();

        StringBuffer buffer = new StringBuffer();

        //This is the recommended way to read the output
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) {
                    break;
                }
                buffer.append(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }

        channel.disconnect();
        session.disconnect();

        Scanner scanner = new Scanner(buffer.toString());
        while (scanner.hasNextLine()){
            String line = scanner.nextLine();
            soundNames.add(line);

            Log.i("SSH", ": " + line);
        }

        return soundNames;
    }


    public void Downloader(String fileName) {

        JSch jsch = new JSch();
        Session session = null;
        Channel channel = null;
        ChannelSftp sftpChannel = null;

        try {

            session = jsch.getSession(user, host, portNum);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(pass);
            session.connect();

            channel = session.openChannel("sftp");
            channel.connect();
            sftpChannel = (ChannelSftp) channel;
            sftpChannel.cd(SFTPWORKINGDIR); //cd to dir that contains file

            try {
                byte[] buffer = new byte[1024];
                BufferedInputStream bis = new BufferedInputStream(sftpChannel.get(fileName));

                File path = Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_DOCUMENTS);
                File newFile = new File(path, "/" + fileName);

                Log.d("Dir" , " " + newFile);

                OutputStream os = new FileOutputStream(newFile);
                BufferedOutputStream bos = new BufferedOutputStream(os);
                int readCount;
                while( (readCount = bis.read(buffer)) > 0) {
                    Log.d("Downloading", " " + fileName );
                    bos.write(buffer, 0, readCount);
                }
                bis.close();
                bos.close();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Log.d( "SUCCESS ", fileName + " has been downloaded!!!!");

            sftpChannel.exit();
            session.disconnect();

        } catch (JSchException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}
公共类MainActivity扩展活动{
私有字符串user=“username”;
私有字符串pass=“password”;
私有字符串host=“主机名”;
私有int-portNum=22;
私有静态最终字符串SFTPWORKINGDIR=“/path/to/file”;
私有字符串文件名;
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
最终ListView列表=(ListView)findViewById(R.id.choose\u sound\u ListView);
新建异步任务(){
@凌驾
受保护列表doInBackground(无效…参数){
试一试{
返回ExecuteMoteCommand(用户、传递、主机、端口号);
}捕获(例外e){
e、 printStackTrace();
}
返回null;
}
@凌驾
public void onPostExecute(列出声音名称){
ArrayAdapter=新的ArrayAdapter(MainActivity.this,android.R.layout.simple\u expandable\u list\u item\u 1,android.R.id.text1,soundNames);
list.setAdapter(适配器);
list.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
公共链接(AdapterView arg0、视图arg1、,
整数位置,长arg3){
字符串newFileName=(字符串)list.getItemAtPosition(位置);
fileName=newFileName;
下载程序(文件名);
//显示警惕
Toast.makeText(getApplicationContext(),
“下载”+文件名,Toast.LENGTH_LONG.show();
}
});
}
}.execute();
}
公共列表ExecuteMoteCommand(字符串用户名、字符串密码、字符串主机名、int端口)引发异常{
List soundNames=new ArrayList();
JSch JSch=新的JSch();
Session Session=jsch.getSession(用户名、主机名、端口);
session.setPassword(密码);
//避免要求钥匙确认
Properties prop=新属性();
道具放置(“检查”、“否”);
session.setConfig(prop);
session.connect();
String command=“ls-la | awk'{print$9}'”;
Channel=session.openChannel(“exec”);
((ChannelExec)channel).setCommand(command);
((ChannelExec)channel.setErrStream(System.err);
InputStream in=channel.getInputStream();
System.out.println(“连接到会话…”);
channel.connect();
StringBuffer=新的StringBuffer();
//这是读取输出的推荐方法
字节[]tmp=新字节[1024];
while(true){
while(in.available()>0){
inti=in.read(tmp,0,1024);
if(i<0){
打破
}
append(新字符串(tmp,0,i));
}
if(channel.isClosed()){
System.out.println(“退出状态:+channel.getExitStatus());
打破
}
试一试{
睡眠(1000);
}捕获(异常ee){
}
}
通道断开();
session.disconnect();
Scanner Scanner=新的扫描仪(buffer.toString());
while(scanner.hasNextLine()){
字符串行=scanner.nextLine();
声音名称。添加(行);
Log.i(“SSH”,“:”+行);
}
返回音名;
}
公共无效下载程序(字符串文件名){
JSch JSch=新的JSch();
会话=空;
通道=空;
ChannelSftp sftpChannel=null;
试一试{
session=jsch.getSession(用户、主机、端口号);
session.setConfig(“StrictHostKeyChecking”、“no”);
session.setPassword(pass);
session.connect();
通道=会话.openChannel(“sftp”);
channel.connect();
sftpChannel=(ChannelSftp)信道;
sftpChannel.cd(SFTPWORKINGDIR);//cd到包含文件的目录
试一试{
字节[]缓冲区=新字节[1024];
BufferedInputStream bis=新的BufferedInputStream(sftpChannel.get(fileName));
文件路径=Environment.getExternalStoragePublicDirectory(
环境。文件目录);
File newFile=新文件(路径“/”+文件名);
Log.d(“Dir”,“newFile”);
OutputStream os=新文件OutputStream(新文件);
BufferedOutputStream bos=新的BufferedOutputStream(os);
整数读取计数;
而((readCount=bis.read(buffer))>0){
Log.d(“下载”和“+文件名);
写入(缓冲区,0,读取计数);
}
二、关闭();
bos.close();
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
Log.d(“成功”,文件名+”已下载!!!!);
sftpChannel.exit();
session.disconnect();
}捕获(JSCHEException e){
e、 printStackTrace();
}捕获(SFTPE例外){
e、 printStackTrace();
}
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.m