File downloaded from Ftp Android (Java)

0

I try to download a file from a web server, but I can not code it "creates" it empty and does not create it with the ftp server data, I use Apache Commons Net API, My problem is in MainActivity > showProductDialog > ftpclient.ftpdownload (), I created an empty file, it should be with information, redirect it to the folder where it is, there is no way to check where exactly my error is with a try catch.

MainActivity

    public class MainActivity extends Activity implements OnClickListener {

    private static final String TAG = "MainActivity";
    private static final String FTP_HOST = "files.000webhost.com";
    private static final String FTP_USER = "mypage"; //Username example
    private static final String FTP_PASS = "12345"; //Password example
    private static final String FTP_DIRECTORIO = "/public_html";
    private static final String TEMP_FILENAME = "test.txt";

    private Context cntx = null;

    private MyFTPClientFunctions ftpclient = null;

    private Button btnLoginFtp, btnUploadFile, btnDisconnect, btnExit, btnProductList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        btnLoginFtp.setOnClickListener(this);
        btnUploadFile.setOnClickListener(this);
        btnProductList.setOnClickListener(this);
        btnDisconnect.setOnClickListener(this);

        ftpclient = new MyFTPClientFunctions();

        public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btnLoginFtp:
                if (isOnline(MainActivity.this)) {
                    connectToFTPAddress();
                } else {
                    Toast.makeText(MainActivity.this,
                            "Porfavor verifica tu conexion a internet!",
                            Toast.LENGTH_LONG).show();
                }
                break;
          case R.id.btnProductList:
                try {
                    showProductDialog(etsrc1.toString(), etsrc2.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this,
                            "ERROR!",
                            Toast.LENGTH_LONG).show();
                }
                Toast.makeText(MainActivity.this,
                        "Intentando descargar!",
                        Toast.LENGTH_LONG).show();

                //Toast.makeText(MainActivity.this, "Archivo descargado", 
            Toast.LENGTH_LONG).show();

                  break;
          case R.id.btnProductList:
                try {
                    showProductDialog(etsrc1.toString(), etsrc2.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this,
                            "ERROR!",
                            Toast.LENGTH_LONG).show();
                }
                Toast.makeText(MainActivity.this,
                        "Intentando descargar!",
                        Toast.LENGTH_LONG).show();

                //Toast.makeText(MainActivity.this, "Archivo descargado", 
                Toast.LENGTH_LONG).show();

                break;
        }
     private void connectToFTPAddress() {

        final String host = FTP_HOST;
        final String username = FTP_USER;
        final String password = FTP_PASS;

       status = ftpclient.ftpConnect(host, username, password, 21);
     }

     private void showProductDialog(String srcfile1, String srcfile2) throws IOException {

     status2 = ftpclient.ftpDownload("test.txt", 
     Environment.getExternalStorageDirectory()+"/public_html/test.txt");
     } 
}

MyFTPClientFunctions

      import java.io.BufferedOutputStream;
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.FileOutputStream;
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.OutputStream;
      import org.apache.commons.net.ftp.FTP;
      import org.apache.commons.net.ftp.FTPClient;
      import org.apache.commons.net.ftp.FTPFile;
      import org.apache.commons.net.ftp.FTPReply;
      import android.content.Context;
      import android.os.Environment;
      import android.util.Log;
      import android.widget.Toast;

      public class MyFTPClientFunctions {

    // Now, declare a public FTP client object.

    private static final String TAG = "MyFTPClientFunctions";
    public FTPClient mFTPClient = null;

    // Method to connect to FTP server:
    public boolean ftpConnect(String host, String username, String password,
                              int port) {
        try {
            mFTPClient = new FTPClient();
            // connecting to the host
            mFTPClient.connect(host, port);

            // now check the reply code, if positive mean connection success
            if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
                // login using username & password
                boolean status = mFTPClient.login(username, password);

                /*
                 * Set File Transfer Mode
                 *
                 * To avoid corruption issue you must specified a correct
                 * transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
                 * EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE for
                 * transferring text, image, and compressed files.
                 */
                mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
                mFTPClient.enterLocalPassiveMode();

                return status;
            }
        } catch (Exception e) {
            Log.d(TAG, "Error: could not connect to host " + host);
        }

        return false;
    }

    // Method to disconnect from FTP server:

    public boolean ftpDisconnect() {
        try {
            mFTPClient.logout();
            mFTPClient.disconnect();
            return true;
        } catch (Exception e) {
            Log.d(TAG, "Error occurred while disconnecting from ftp server.");
        }

        return false;
    }

    // Method to get current working directory:

    public String ftpGetCurrentWorkingDirectory() {
        try {
            String workingDir = mFTPClient.printWorkingDirectory();
            return workingDir;
        } catch (Exception e) {
            Log.d(TAG, "Error: could not get current working directory.");
        }

        return null;
    }

    // Method to change working directory:

    public boolean ftpChangeDirectory(String directory_path) {
        try {
            mFTPClient.changeWorkingDirectory(directory_path);
        } catch (Exception e) {
            Log.d(TAG, "Error: could not change directory to " + directory_path);
        }

        return false;
    }

    // Method to list all files in a directory:

    public String[] ftpPrintFilesList(String dir_path) {
        String[] fileList = null;
        try {
            FTPFile[] ftpFiles = mFTPClient.listFiles(dir_path);
            int length = ftpFiles.length;
            fileList = new String[length];
            for (int i = 0; i < length; i++) {
                String name = ftpFiles[i].getName();
                boolean isFile = ftpFiles[i].isFile();

                if (isFile) {
                    fileList[i] = "File :: " + name;
                    Log.i(TAG, "File : " + name);
                } else {
                    fileList[i] = "Directory :: " + name;
                    Log.i(TAG, "Directory : " + name);
                }
            }
            return fileList;
        } catch (Exception e) {
            e.printStackTrace();
            return fileList;
        }
    }

    // Method to create new directory:

    public boolean ftpMakeDirectory(String new_dir_path) {
        try {
            boolean status = mFTPClient.makeDirectory(new_dir_path);
            return status;
        } catch (Exception e) {
            Log.d(TAG, "Error: could not create new directory named "
                    + new_dir_path);
        }

        return false;
    }

    // Method to delete/remove a directory:

    public boolean ftpRemoveDirectory(String dir_path) {
        try {
            boolean status = mFTPClient.removeDirectory(dir_path);
            return status;
        } catch (Exception e) {
            Log.d(TAG, "Error: could not remove directory named " + dir_path);
        }

        return false;
    }

    // Method to delete a file:

    public boolean ftpRemoveFile(String filePath) {
        try {
            boolean status = mFTPClient.deleteFile(filePath);
            return status;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    // Method to rename a file:

    public boolean ftpRenameFile(String from, String to) {
        try {
            boolean status = mFTPClient.rename(from, to);
            return status;
        } catch (Exception e) {
            Log.d(TAG, "Could not rename file: " + from + " to: " + to);
        }

        return false;
    }

    // Method to download a file from FTP server:

    /**
     * mFTPClient: FTP client connection object (see FTP connection example)
     * srcFilePath: path to the source file in FTP server desFilePath: path to
     * the destination file to be saved in sdcard
     */
    public boolean ftpDownload(String srcFilePath, String desFilePath) {
        boolean status = false;
        try {
            FileOutputStream desFileStream = new FileOutputStream(desFilePath);
            ;
            status = mFTPClient.retrieveFile(srcFilePath, desFileStream);
            desFileStream.close();

            return status;
        } catch (Exception e) {
            Log.d(TAG, "download failed");

        }

        return status;
    }
    public boolean descargar() throws IOException {
        // File #1 download
        Boolean success = false;
        String remoteFile2 = "/public_html/online.txt";
        File downloadFile2 = new File(Environment.getExternalStorageDirectory()+"/public_html/online.txt");
        OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(downloadFile2));
        InputStream inputStream1 = mFTPClient.retrieveFileStream(remoteFile2);
        byte[] bytesArray = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream1.read(bytesArray)) != -1) {
            outputStream2.write(bytesArray, 0, bytesRead);
        }

        success = mFTPClient.completePendingCommand();
        if (success) {
            System.out.println("File #2 has been downloaded successfully.");
        }
        outputStream2.close();
        inputStream1.close();

        // Code 2
        return true;
    }
    // Method to upload a file to FTP server:

    /**
     * mFTPClient: FTP client connection object (see FTP connection example)
     * srcFilePath: source file path in sdcard desFileName: file name to be
     * stored in FTP server desDirectory: directory path where the file should
     * be upload to
     */
    public boolean ftpUpload(String srcFilePath, String desFileName,
                             String desDirectory, Context context) {
        boolean status = false;
        try {
            FileInputStream srcFileStream = new FileInputStream(srcFilePath);

            // change working directory to the destination directory
            // if (ftpChangeDirectory(desDirectory)) {
            status = mFTPClient.storeFile(desFileName, srcFileStream);
            // }

            srcFileStream.close();

            return status;
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "upload failed: " + e);
        }

        return status;
    }
}
    
asked by Andres Gaibor 03.05.2018 в 06:08
source

1 answer

0

It is necessary for the operations to be done by creating a new thread outside the main one:

new Thread(new Runnable() {
    public void run() {
           // ...
        }
    } }).start();

For example:

new Thread(new Runnable() {
    public void run() {
        boolean status = false;

        // conexion al servidor
        status = ftpclient.ftpConnect(host, username, password, 21);

        if (status) {
            Log.d(TAG, "Conexion establecida");    
        } else {
            Log.d(TAG, "La conexion ha fallado");
        }
    }
}).start();

The same to download the FTP server file:

new Thread(new Runnable() {
    public void run() {
           showProductDialog(etsrc1.toString(), etsrc2.toString());
        }
    } }).start();

You can also use a AsynTask :

 private class ConnFTP extends AsyncTask<Void , Integer, Long>
    {
        @Override
        protected Long doInBackground(Void... voids) {
            // Inicia proceso
            return null;
        }

        @Override
        protected void onPostExecute(Long result) {
          // Termina el proceso
            Log.i("TAG" , "Termina el proceso.");
        }
    }
    
answered by 03.05.2018 в 10:13