Apache Commons FTP not writing to FileOutputStream with no error thrown

74 views Asked by At

I am using the apache commons library in an android app that we have developed. This is legacy code, and for some reason, it is not writing to the device. This is happening on multiple devices, so it's not device specific. We are using Nexus 7 devices running Android 4.4.

The routine basically FTPs to our server and looks for new images to download. FTP into server is successful, no problems there.

String listOfFiles = "GE_PT17_image.png,GE_PT18_image.png,GE_PT39_image.png";
String devicePathName = "/mnt/sdcard/company_name/DRMHH/"
status = ftpConnect(args[2], args[0], args[1], 21);
mFTPClient.changeWorkingDirectory(pathname);

FTPFile[] files = mFTPClient.listFiles();

We basically look at all the images in the directory on the server, then match them to the desired images:

for (int i = 0; i < files.length; i++) {
    if (files[i].isDirectory()) {
                            ;

    } else {
    ///mnt/sdcard/company_name/DRMHH/

   if (listOfFiles.toUpperCase().contains(files[i].getName().toUpperCase())) {
        File file = new File(devicePathName + File.separator + files[i].getName());
        Log.d("FileName", devicePathName + File.separator + files[i].getName());
        try {
            FileOutputStream fos = new FileOutputStream(file); //NO ERROR or EXCEPTION
            boolean weAreOK = mFTPClient.retrieveFile(files[i].getName(), fos); //returns true
            fos.flush();
            fos.close();
        } catch (Exception e) {
                Log.d("File Exception", e.toString());
        }

    }
  }

 }

No files are found on the device that were supposedly downloaded. The variable returning whether file was successfully retrieved returns true. Like I said, this is legacy code that has been around for years and until now worked with no problems. Anyone have any ideas?

1

There are 1 answers

2
CommonsWare On BEST ANSWER

The protocol used over the USB connection, since Android 3.0, is the Media Transfer Protocol (MTP). The files served by Android over MTP are not what is on the filesystem, but rather what is indexed by the MediaStore.

Files that you create on external storage will eventually be indexed and added to the MediaStore. The key word is "eventually".

So, that means three things:

  1. Please call getFD().sync() on your FileOutputStream after flush() and before close(). This ensures that the files are written to disk before continuing.

  2. Use MediaScannerConnection and scanFile() after close(), to tell MediaStore about the newly-created file, rather than waiting for the file to be indexed automatically at some arbitrary time in the future.

  3. If you continue having problems, double check using DDMS's file explorer or adb shell whether the files are there, rather than relying solely on MTP.