English 中文(简体)
上传或下载从/下载到 ftp 服务器: Android 客户端
原标题:Upload or Download from/to ftp server: Android Client
  • 时间:2012-05-27 19:21:12
  •  标签:
  • android
  • ftp

I m working on android project to test FTP functions both upload or download files. Here s my first try code based on this tutorial:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    try {
        SimpleFTP ftp = new SimpleFTP();

        // Connect to an FTP server on port 21.
        ftp.connect("ftp.olympe-network.com", 21, "username", "password");


        // Set binary mode.
        ftp.bin();

        // Change to a new working directory on the FTP server.
        ftp.cwd("web");

        // Upload some files.
        ftp.stor(new File("shirt.jpg"));
        //ftp.stor(new File("comicbot-latest.png"));

        // You can also upload from an InputStream, e.g.
        ftp.stor(new FileInputStream(new File("shirt.jpg")), "shirt.jpg");
        /*ftp.stor(someSocket.getInputStream(), "blah.dat");
        */

        // Quit from the FTP server.
        ftp.disconnect();
    }
    catch (IOException e) {
        // Jibble.
    }
}

我的 shirt.jpg 文件在主工程文件夹中存储。 i 使用模拟器不是物理设备。 我日志中没有错误, 但文件没有上传 。

然后,我改换了另一种方法:

private void loadLogs() {
    //radBtn.addView(null);
    new processTask().execute();
}
private class processTask extends AsyncTask<String, Void, Void>{
    private ProgressDialog Dialog = new ProgressDialog(activitiMain.this);
     private TextView log; 
     private  Spinner s;
    protected void onPreExecute() {
        Dialog.setMessage("Loading...");
        Dialog.show();
    }
    @Override
    protected Void doInBackground(String... arg0) {
        FTPClient client = new FTPClient();
        try {
        SharedPreferences myPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        String ipaddr = myPref.getString("etServer", "");
        String port= myPref.getString("port", "21");
        String logFile= myPref.getString("logfname", "error_log");
        String filePath= myPref.getString("path", "/public_html");
        String uname= myPref.getString("uname", "");
        String pass= myPref.getString("pass", "");
        client.connect(ipaddr,21);
        client.enterLocalPassiveMode();
        boolean login = client.login(uname, pass);
        client.changeWorkingDirectory(filePath);
        System.out.println(client.printWorkingDirectory());

        BufferedReader reader = null;
        String line = null;
        sv = new ScrollView(activitiMain.this);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
        sv.setLayoutParams(LP_FF);
        LinearLayout loglay  =  new LinearLayout(activitiMain.this);
        loglay.setOrientation( LinearLayout.VERTICAL );  //FTPFile[] ftpFiles = client.listFiles();
        FTPFile[] ftpFiles = client.listFiles();
        ArrayList<String> name = new ArrayList<String>();                              
        ArrayAdapter <CharSequence> adapter =new ArrayAdapter <CharSequence> (getBaseContext(), android.R.layout.simple_spinner_item );
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

             adapter.add("Select File");*/      
            //s = new (Spinner)findViewById(R.id.Spinner01);
            s = new Spinner(activitiMain.this);
            for (int i = 0; i < ftpFiles.length; i++) { 
                String fname =ftpFiles[i].getName();
                Log.i("FTP", "File " +i +" : "+fname);
                       name.add(fname);
                        long length = ftpFiles[i].getSize();
                        //adapter2.add(ftpFiles[i].getName());
                        //String readableLength = FileUtils.byteCountToDisplaySize( length );
                        ///System.out.println( name + ":		" + readableLength );  
                    }
            //String [] strArray =null;
            //strArray.toArray(name);
            String [] files = name.toArray(new String[name.size()]);
            @SuppressWarnings("unchecked")
            ArrayAdapter<Object> adapter2 = new ArrayAdapter<Object>(getApplicationContext(), android.R.layout.simple_spinner_item,files);  
             adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
             s.setAdapter(adapter2);  
             loglay.addView(s);

         Log.i("Files", ftpFiles.toString());
            for (FTPFile ftpFile : ftpFiles) {
                String fileName = ftpFile.getName(); 
                if (fileName.equals(logFile)){
                     try {
                         InputStream stream = client.retrieveFileStream(fileName);                             
                         reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
                         //line = reader.readLine();


                         while ((line = reader.readLine())!= null && line.trim().length()>0) {
                                //System.out.println(line);
                             log = new TextView(activitiMain.this);
                                String trail = line; 
                                log.setTextColor(Color.GREEN);                                                                                                                                                                                                                                                                                                                                 
                                log.setPadding(10, 5, 0, 5);
                                log.setText(trail);                                                                                                                                                                                                                                                                                                                                   
                                loglay.addView(log);    
                            }
                         sv.addView(loglay);
                     } finally {
                         if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
                     }
                }
            }
               client.logout();


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    protected void onPostExecute(Void unused) {
        Dialog.dismiss();
        setContentView(sv);
        }

在我首选屏幕中, 我指定了 ftp 服务器参数, 但我在日志中也有一个错误 :

    05-27 18:36:38.237: ERROR/AndroidRuntime(585): FATAL EXCEPTION: main
05-27 18:36:38.237: ERROR/AndroidRuntime(585): java.lang.NullPointerException
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at android.view.ViewGroup.addViewInner(ViewGroup.java:1969)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at android.view.ViewGroup.addView(ViewGroup.java:1865)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at android.view.ViewGroup.addView(ViewGroup.java:1845)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:217)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at android.app.Activity.setContentView(Activity.java:1658)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at com.sam.remote.activitiMain$processTask.onPostExecute(activitiMain.java:160)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at com.sam.remote.activitiMain$processTask.onPostExecute(activitiMain.java:1)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at android.os.AsyncTask.finish(AsyncTask.java:417)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at android.os.Looper.loop(Looper.java:123)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at android.app.ActivityThread.main(ActivityThread.java:4627)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at java.lang.reflect.Method.invokeNative(Native Method)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at java.lang.reflect.Method.invoke(Method.java:521)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-27 18:36:38.237: ERROR/AndroidRuntime(585):     at dalvik.system.NativeStart.main(Native Method)
问题回答

当您在这里查看您的第一个尝试时, 当你说您的文件 shirt.jpg 存储在您的主工程文件夹中时, 我不认为您的代码会发现一旦被安装到设备上, 您可能就得手动在设备上存储文件, 正如这里所解释的 :

http://developers.android.com/guide/topics/data/data-storage.html#files Internal

或者您可以先将 shirt.jpg 文件 (trough ADP) 上传到您的应用程序共享目录上, 正如在此解释的 :

http://developer.android.com/guide/topics/data/data-storage.html#files outternal

然后试着读读它,然后FTP它。

哦,是的,我的经验 保存文件 关于Android,然后电子邮件, 使用一个实际的设备测试 因为模拟器 不提供您需要的网络连接。

私人类 FtpTashsk 延伸 AsyncTask< DocumentFile、 Void、 Void> { 扩展 AsyncTask< DocumentFile、 Void、 Void> {

    @Override
    protected Void doInBackground(DocumentFile... documentFiles) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(SERVER);
            ftpClient.login(USERNAME, PASSWORD);

            // Upload the file from the device to the FTP server
            uploadFile(ftpClient, documentFiles[0]);
            isUploadSuccessful = true;
            // Download the file from the FTP server to the app s private files directory
            downloadFile(ftpClient);

            // Disconnect after the upload and download
            ftpClient.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            showToast("Error: " + e.getMessage());
        }
        return null;
    }

    private void uploadFile(FTPClient ftpClient, DocumentFile pickedFile) throws IOException {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();

        // Create an InputStream for the picked file
        try (InputStream inputStream = getContentResolver().openInputStream(pickedFile.getUri())) {
            // Specify the remote file name on the server
            ftpClient.storeFile(REMOTE_FILE_NAME, inputStream);
            showToast("File uploaded successfully to: " + REMOTE_FILE_NAME);
        }
    }

    private void downloadFile(FTPClient ftpClient) throws IOException {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();

        // Specify the remote file name on the server
        String remoteFileName = REMOTE_FILE_NAME;

        // Create an InputStream to read the file from the FTP server
        try (InputStream inputStream = ftpClient.retrieveFileStream(remoteFileName)) {
            if (inputStream != null) {
                // Save the file to the app s private files directory
                saveToFile(inputStream);
                showToast("File downloaded successfully to: " + getFilesDir() + "/" + remoteFileName);
            } else {
                showToast("Error downloading file: " + ftpClient.getReplyString());
            }
        }
    }

在您的代码中使用此代码片断

private static final String SERVER = "115.111.229.10"; private static final String USERNAME = "rnd"; private static final String PASSWORD = "rnd123"; replace these values with your values

在哪个行发生例外? 双击错误消息并尝试再次调试/ 挂出





相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签