android中的ftp客户端问题

时间:2013-12-30 11:38:09

标签: android ftp

我尝试使用FTP协议将图像文件从我的Android应用程序上传到我的服务器..

我在互联网上发现了这个课程,但工作不正常。

这是我的代码:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class FileUpload {

/**
 * Upload a file to a FTP server. A FTP URL is generated with the following
 * syntax: ftp://user:password@host:port/filePath;type=i.
 * 
 * @param ftpServer
 *            , FTP server address (optional port ':portNumber').
 * @param user
 *            , Optional user name to login.
 * @param password
 *            , Optional password for user.
 * @param fileName
 *            , Destination file name on FTP server (with optional preceding
 *            relative path, e.g. "myDir/myFile.txt").
 * @param source
 *            , Source file to upload.
 * @throws MalformedURLException
 *             , IOException on error.
 */
public FileUpload() {
}

public void upload(String ftpServer, String user, String password,
        String fileName, File source) throws MalformedURLException,
        IOException {
    if (ftpServer != null && fileName != null && source != null) {
        StringBuffer sb = new StringBuffer("ftp://");
        // check for authentication else assume its anonymous access.
        if (user != null && password != null) {
            sb.append(user);
            sb.append(':');
            sb.append(password);
            sb.append('@');
        }
        sb.append(ftpServer);
        sb.append('/');
        sb.append(fileName);
        /*
         * type ==> a=ASCII mode, i=image (binary) mode, d= file
         * directory listing
         */
        sb.append(";type=i");

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {

            URL url = new URL(sb.toString());
            URLConnection urlc = url.openConnection();

            bos = new BufferedOutputStream(urlc.getOutputStream()); ///here i get an exception
            bis = new BufferedInputStream(new FileInputStream(source));

            int i;
            // read byte by byte until end of stream
            while ((i = bis.read()) != -1) {
                bos.write(i);
            }
        } finally {
            if (bis != null)
                try {
                    bis.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            if (bos != null)
                try {
                    bos.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
        }
    } else {
        System.out.println("Input not available.");
    }
}

我如何解决这个问题? 注意:我从另一个线程(而不是主线程)调用此方法..

0 个答案:

没有答案