Question

Hi I am trying to connect FTP and read a file and generate md5 checksum value for that file, but I am facing Stream Closed error. Here is my code.

import java.io.FileInputStream;
import java.security.MessageDigest;
import java.util.Properties;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.commons.net.ftp.FTPClient;

MessageDigest digest = MessageDigest.getInstance("MD5");

FTPClient ftp=new FTPClient();
ftp.enterLocalPassiveMode();
ftp.connect("address");
ftp.login('username','password');
InputStream iStream=ftp.retrieveFileStream("path of the file");
BufferedInputStream bInf=new BufferedInputStream(iStream);
byte[] buffer = new byte[8192];    
int read = 0;
while ((read = bInf.read(buffer)) !=-1)
{
digest.update(buffer, 0, read);
};

byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum)
def x=bigInt.toString(16).padLeft(32,'0')

Kindly help me where I went wrong

Was it helpful?

Solution

I got it to work with the following code:

import java.security.MessageDigest
import org.apache.commons.net.ftp.FTPClient

MessageDigest digest = MessageDigest.getInstance("MD5")

String md5 = new FTPClient().with { ftp ->
    try {
        ftp.enterLocalPassiveMode()
        ftp.connect( address )
        ftp.login( username, password )
        ftp.retrieveFileStream( path ).with { ins ->
            if( ins == null ) {
                println "ERROR: $ftp.replyCode '${ftp.replyString.trim()}'"
            }
            else {
                try {
                    ins.eachByte( 8192 ) { buffer, nbytes ->
                        digest.update( buffer, 0, nbytes )
                    }
                    digest.digest().encodeHex().toString().padLeft( 32, '0' )
                }
                finally {
                    ins.close()
                }
            }
        }
    }
    finally {
        ftp.disconnect()
    }
}

(assuming you have variables defined for address, username, password and path)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top