Android FTP 上传下传文件

如果自己没有FTP服务器,可以到www.5944.net上面去申请一个,申请速度很快,申请了既可以用了.

我提供一个我自己申请的:

FTP服务器:
您的FTP用户名:	durian
您的FTP密码是:	7389A913676fdf
您的网址为:	http://durian
您的FTP地址是:	freehost.22u2.cn
服务器IP是:	freehost.22u2.cn
到期时间是:	2016/2/12 13:58:07

不过时间太短了,只能够使用一个月.

FTP查看工具:8utfp

这个用来判断上传的文件是否的确在服务器上面了,可以通过它查看.


简单的东西就不多扯淡了,直接上程序:

<1> : 新建Android工程:


<2>  具体的程序如下:

DurianMainActivity.java
package org.durian.durianftp;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.durian.durianftp.ftp.Ftp;

public class DurianMainActivity extends ActionBarActivity implements View.OnClickListener {

    private final static String TAG="DurianMainActivity";

    private final static String FTP_NAME="durian";
    private final static String FTP_PWD="7389A913676fdf";
    private final static String FTP_URL="freehost.22u2.cn";
    private final static String FTP_REMOTE="/durian/web/";
    private final static String FTP_FILE_PATH="/sdcard/";
    private final static String FTP_FILE_NAME="backup_70-01-02_004832.json";
    private final static String FTP_PORT="21";
    private final static String FTP_REMOTE_FILE="/durian/web/index.htm";
    private final static String FTP_LOCALPATH="/sdcard/web123web123web123web123web123web123web123.html";

    private EditText mUrlEdit;
    private EditText mPortEdit;
    private EditText mUserEdit;
    private EditText mPassEdit;
    private EditText mRemoteEdit;
    private EditText mFPathEdit;
    private EditText mFNameEdit;

    private Button mCancelButton;
    private Button mLoginButton;

    private Button mDownLoadButton;

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

        mUrlEdit=(EditText)findViewById(R.id.urledit);
        mUrlEdit.setText(FTP_URL);

        mPortEdit=(EditText)findViewById(R.id.portedit);
        mPortEdit.setText(FTP_PORT);

        mUserEdit=(EditText)findViewById(R.id.usernameedit);
        mUserEdit.setText(FTP_NAME);

        mPassEdit=(EditText)findViewById(R.id.paswordedit);
        mPassEdit.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
        mPassEdit.setText(FTP_PWD);

        mRemoteEdit=(EditText)findViewById(R.id.remoteedit);
        mRemoteEdit.setText(FTP_REMOTE);

        mFPathEdit=(EditText)findViewById(R.id.fpathedit);
        mFPathEdit.setText(FTP_FILE_PATH);

        mFNameEdit=(EditText)findViewById(R.id.fnameedit);
        mFNameEdit.setText(FTP_FILE_NAME);

        mCancelButton=(Button)findViewById(R.id.cancel);
        mLoginButton=(Button)findViewById(R.id.upload);
        mCancelButton.setOnClickListener(this);
        mLoginButton.setOnClickListener(this);

        mDownLoadButton=(Button)findViewById(R.id.download);
        mDownLoadButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        int id=v.getId();

        switch (id){
            case R.id.cancel:
                break;
            case R.id.upload:
                /*Ftp.ftpUpload(mUrlEdit.getText().toString(),mPortEdit.getText().toString(),
                        mUserEdit.getText().toString(),mPassEdit.getText().toString(),
                        mRemoteEdit.getText().toString(),mFPathEdit.getText().toString(),mFNameEdit.getText().toString());*/

                mUploadFile2FTP.execute(FTP_URL,FTP_PORT,FTP_NAME,FTP_PWD,FTP_REMOTE,FTP_FILE_PATH,FTP_FILE_NAME);

                break;
            case R.id.download:

                mdownLoadFileFromFTP.execute(FTP_URL,FTP_PORT,FTP_NAME,FTP_PWD,FTP_REMOTE_FILE,FTP_LOCALPATH);

                break;
            default:
                break;
        }
    }

    private downLoadFileFromFTP mdownLoadFileFromFTP=new downLoadFileFromFTP();
    private class downLoadFileFromFTP extends AsyncTask<String,Integer,String>{

        @Override
        protected String doInBackground(String... params) {

            Log.i(TAG,"********************************************************");

            boolean isOK=Ftp.downLoadFromFTP(FTP_URL,FTP_PORT,FTP_NAME,FTP_PWD,FTP_REMOTE_FILE,FTP_LOCALPATH);

            if(isOK){
                Log.i(TAG,"File Name : "+FTP_REMOTE_FILE+" have already download from your FTP server successfully !");
            }else{
                Log.i(TAG,"File Name : "+FTP_REMOTE_FILE+" can not download from your FTP server !");
            }

            return isOK?"true":"false";
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }

    private upLoadFile2FTP mUploadFile2FTP=new upLoadFile2FTP();
    private class upLoadFile2FTP extends AsyncTask<String,Integer,String>{

        @Override
        protected String doInBackground(String... params) {

            for(int i=0;i<params.length;i++){
                Log.i(TAG,"params["+i+"] : "+params[i]);
            }

            publishProgress(50);

            String isOK=Ftp.ftpUpload(FTP_URL,FTP_PORT,FTP_NAME,FTP_PWD,FTP_REMOTE,FTP_FILE_PATH,FTP_FILE_NAME);

            if(isOK.contains("1")){
                Log.i(TAG,"File Name : "+FTP_FILE_NAME+" have already upload to your FTP server successfully !");
            }else{
                Log.i(TAG,"File Name : "+FTP_FILE_NAME+" can not upload to your FTP server !");
            }

            publishProgress(100);
            return isOK;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            Log.i(TAG,"onPostExecute result : "+s);

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.i(TAG,"onPreExecute");
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Log.i(TAG,"onProgressUpdate values : "+values[0]);
        }

    }

}

Ftp.java
package org.durian.durianftp.ftp;

import android.util.Log;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Project name : DurianFtp
 * Created by zhibao.liu on 2016/1/12.
 * Time : 9:24
 * Email warden_sprite@foxmail.com
 * Action : durian
 */
public class Ftp {

    private final static String TAG="FTP";

    public static String ftpUpload(String url, String port, String username, String password, String remotePath, String filenamepath, String filename) {

        FTPClient ftpClient = new FTPClient();
        FileInputStream fis=null;
        String retMessage="0";

        try {
            ftpClient.connect(url,Integer.parseInt(port));
            boolean loginResult=ftpClient.login(username,password);
            int retCode=ftpClient.getReplyCode();
            if(loginResult && FTPReply.isPositiveCompletion(retCode)){
                ftpClient.makeDirectory(remotePath);
                ftpClient.changeWorkingDirectory(remotePath);
                ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("UTF-8");
                ftpClient.enterLocalPassiveMode();
                fis=new FileInputStream(filenamepath+filename);
                ftpClient.storeFile(filename,fis);

                retMessage="1";

                Log.i(TAG,"retMessage : 1");

            }else{
                retMessage="0";
                Log.i(TAG,"retMessage : 0");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return retMessage;

    }

    public static boolean downLoadFromFTP(String url, String port, String username, String password, String remotePath,String localpath){

        FTPClient ftpClient=new FTPClient();
        InputStream is=null;
        FileOutputStream io=null;
        File file=new File(localpath);

        byte[] buffer=new byte[1024];

        int currentlength=0;
        int len=0;

        try {

            ftpClient.connect(url,Integer.parseInt(port));
            boolean loginResult=ftpClient.login(username,password);
            int retCode=ftpClient.getReplyCode();

            //following programe is very important
            //setting it is neccessary
            ftpClient.enterLocalPassiveMode();

            if(!FTPReply.isPositiveCompletion(retCode)) {
                ftpClient.disconnect();
                Log.i(TAG,"FTP server refused connection.");
                System.exit(1);
            }

            if(loginResult && FTPReply.isPositiveCompletion(retCode)){

                is=ftpClient.retrieveFileStream(remotePath);
                io=new FileOutputStream(file,false);

                while((len=is.read(buffer))!=-1){

                    io.write(buffer,0,len);
                    currentlength=currentlength+len;
                    Log.i(TAG,"download "+currentlength+" byte");

                }

                is.close();
                io.close();

            }

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

        return true;
    }

}


durian_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="org.durian.durianftp.DurianMainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="URL : " />

        <EditText
            android:id="@+id/urledit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="#ffeeff" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="PORT : " />

        <EditText
            android:id="@+id/portedit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="#ffeeff" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="USERNAME : " />

        <EditText
            android:id="@+id/usernameedit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="#ffeeff" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="PASSWORD : " />

        <EditText
            android:id="@+id/paswordedit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="#ffeeff" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="REMOTE : " />

        <EditText
            android:id="@+id/remoteedit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="#ffeeff" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="FPATH : " />

        <EditText
            android:id="@+id/fpathedit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="#ffeeff" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="FNAME : " />

        <EditText
            android:id="@+id/fnameedit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="#ffeeff" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_weight="3">

        <Button
            android:id="@+id/cancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Clear"/>

        <Button
            android:id="@+id/upload"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="upload"/>

        <Button
            android:id="@+id/download"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="download"/>

    </LinearLayout>

</LinearLayout>

<3> : 运行结果:

下载到sdcard的

上传到ftp服务器的


即可以了.


注意android工程manifest里面配置权限:

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值