Android从ftp服务器获取文件

Posted 勇敢地追

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android从ftp服务器获取文件相关的知识,希望对你有一定的参考价值。

window搭建ftp服务器的步骤在这里,亲测可行:
http://blog.sina.com.cn/s/blog_3f7e47f20100haur.html
主要留意一下绑定的ip地址,以后要用到

要想从ftp服务器获取文件还要用到一个ftp4j的jar包。官网:http://www.sauronsoftware.it/projects/ftp4j/。可以把它先下载下来再参考/doc/manual.en.html来使用

1.把解压出来的jar文件放到libs目录中去

2.布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.getpkgfromftp.MainActivity" >

    <!-- ip地址 -->

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/ip"
        android:textSize="30sp" />

    <!-- 端口号 -->

    <TextView
        android:id="@+id/pkgRoute"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/port"
        android:textSize="30sp" />

    <!-- 用户名 -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:focusableInTouchMode="true" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/username"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/etUserName"
            android:layout_width="0sp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:drawable/edit_text"
            android:hint="@string/username"
            android:text="@string/user"
            android:textSize="20sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/_suffix"
            android:textSize="20sp" />
    </LinearLayout>

    <!-- 密码 -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:focusableInTouchMode="true" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/pwd"
            android:textSize="20sp" />

        <EditText
            android:id="@+id/etPwd"
            android:layout_width="0sp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:drawable/edit_text"
            android:hint="@string/default_pwd"
            android:text="@string/default_pwd"
            android:textSize="20sp" />
    </LinearLayout>

    <Button
        android:id="@+id/btnGet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/get" />

    <!-- 用来显示ftp服务器里面的文件列表 -->

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

</LinearLayout>

3.mainactivity

package com.example.getpkgfromftp;

import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;

import java.io.File;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity 
    /** 只需要ip地址,不需要前面的ftp:// */
    private static final String HOST = "";
    private static final int PORT = 21;
    private String USERNAME = "";
    private String PASSWORD = "";

    private ListView listView;
    private ArrayAdapter<String> adapter;

    private FTPClient client;

    private Handler handler = new Handler() 
        @Override
        public void handleMessage(Message msg) 
            if (msg.what == 0x001) 
                adapter.add((String) msg.obj);
             else if (msg.what == 0x002) 
                Toast.makeText(MainActivity.this,
                        "connect fail", Toast.LENGTH_SHORT)
                        .show();
            
        
    ;

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

        USERNAME = ((EditText) findViewById(R.id.etUserName)).getText()
                .toString();
        USERNAME += "@***.com";//这里是你的域名。一般公司给员工分配的用户名都有@的后缀
        PASSWORD = ((EditText) findViewById(R.id.etPwd)).getText().toString();
        Log.i("USERNAME", USERNAME);
        Log.i("PASSWORD", PASSWORD);

        listView = (ListView) findViewById(R.id.listView1);
        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1);
        listView.setAdapter(adapter);
        ((Button) findViewById(R.id.btnGet))
                .setOnClickListener(new OnClickListener() 
                    @Override
                    public void onClick(View v) 
                        adapter.clear();
                        new Thread(new Runnable() 
                            @Override
                            public void run() 
                                client = new FTPClient();
                                try 
                                    client.connect(HOST, PORT);
                                    client.login(USERNAME, PASSWORD);
                                    String[] file = client.listNames();
                                    for (int i = 0; i < file.length; i++) 
                                        Log.i("file", file[i]);
                                        Message message = handler
                                                .obtainMessage(0x001, file[i]);
                                        handler.sendMessage(message);
                                    
                                 catch (Exception e) 
                                    handler.sendEmptyMessage(0x002);
                                    return;
                                
                            
                        ).start();
                    
                );
        /**
         * commons-net-3.0.1.jar 
         * listNames返回NULL,list返回Int,listFiles返回NULL
         * 因为传进去的参数是(String)null
         * 自己可以去了解,我这里就不演示了
         */

        listView.setOnItemClickListener(new OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    final int position, long id) 
                String dir = Environment.getExternalStorageDirectory()
                        + "/test/";
                File fileDir = new File(dir);
                if (!fileDir.exists()) 
                    fileDir.mkdirs();
                
                String path = dir + adapter.getItem(position);
                final File file = new File(path);
                if (file.exists()) 
                    file.delete();
                    Log.i("delete", "original file deleted");
                
                try 
                    new Thread(new Runnable() 
                        @Override
                        public void run() 
                            try 
                                // 参考/doc/manual.en.html,最后面的参数是监听器
                                client.download(adapter.getItem(position),
                                        file, new MyTransferListener());
                             catch (Exception e) 
                                e.printStackTrace();
                            
                        
                    ).start();
                 catch (Exception e) 
                    e.printStackTrace();
                
            
        );
    

    public class MyTransferListener implements FTPDataTransferListener 
        public void started() 
            Log.i("download", "download start");
        

        public void transferred(int length) 
            Log.i("download", "have download " + length + " bytes");
        

        public void completed() 
            Log.i("download", "download completed");
        

        public void aborted() 
            Log.i("download", "download aborted");
        

        public void failed() 
            Log.i("download", "download failed");
        
    

4.权限

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

以上是关于Android从ftp服务器获取文件的主要内容,如果未能解决你的问题,请参考以下文章

从 ftp 连接中获取文件

从FTP服务器获取文件并将其复制到UNC目录

如何流式传输从 FTP 获取的文件而不将其存储在本地?

如何从 .NET 应用程序中的 FTP 协议获取目录文件大小

java在浏览器上获取FTP读文件路径

linux 自动登录ftp 获取文件