Search code examples
javaftpputftp-client

How to trap ftp success/failure in sun.net.ftp.FtpClient?


I want to know if really 'put' has succeeded in putting the file to destination. If for any reason the file is not put in destination [maybe due to problems in destination server like space constraint, etc] I need to know that.

Code:

    private static boolean putFile(String m_sLocalFile, FtpClient m_client) {
            boolean success = false;
    int BUFFER_SIZE = 10240;
    if (m_sLocalFile.length() == 0) {
        System.out.println("Please enter file name");
    }
    byte[] buffer = new byte[BUFFER_SIZE];
    try {
        File f = new File(m_sLocalFile);
        int size = (int) f.length();
        System.out.println("File " + m_sLocalFile + ": " + size + " bytes");
        System.out.println(size);
        FileInputStream in = new FileInputStream(m_sLocalFile);
        OutputStream out = m_client.put(f.getName());

        int counter = 0;
        while (true) {
            int bytes = in.read(buffer);
            if (bytes < 0)
                break;
            out.write(buffer, 0, bytes);
            counter += bytes;
            System.out.println(counter);
        }

        out.close();
        in.close();
    } catch (Exception ex) {
        System.out.println("Error: " + ex.toString());
    }
          return success;
}

Solution

  • I would expect it to throw an IOException. Do you have any reason to believe it doesn't? But you shouldn't be using that class directly, you should be using an ftp: URL and its URLConnection class to do the I/O with, after calling setDoOutput(true).