Java – Sending database via ftp – Get different files

Sending database via ftp – Get different files… here is a solution to the problem.

Sending database via ftp – Get different files

I’m currently using this code to send a database via ftp (using Apache Commons).

File file = getDatabasePath("database");

FTPClient ftp = new FTPClient();

try {
    ftp.connect(InetAddress.getByName(domain));
    ftp.login(username, password);
    ftp.setFileType(FTP. BINARY_FILE_TYPE);
    FileInputStream is = new FileInputStream(file);
    BufferedInputStream buffIn = new BufferedInputStream(is);
    ftp.enterLocalPassiveMode();
    ftp.storeFile("database", buffIn);
    buffIn.close();
    ftp.logout();
    ftp.disconnect();
} catch (Exception e) {
     TODO: handle exception
}

I used it to send a text file and it works. However, I’ve tried it with my database, a file of the same size is put on the server, but when I open it, the SQLite browser doesn’t show anything. It works well for very small databases, but I run into this issue once the database gets bigger.

I wonder if this is related to buffer size? Can anyone shed light on why this is happening?

Thanks

Solution

The code you posted does not apply to files that are not suitable for buffering input stream buffers. What you need to do is repeat the read from the input stream until the end:

ftp.enterLocalPassiveMode();
ftp.storeFile("database", buffIn);
byte[] buffer = new byte[8192];
OutputStream os = ftp.storeFileStream("database");
int readCount = 0;
while ((readCount = buffIn.read(buffer)) > 0) {
    os.write(buffer, 0, readCount);
}
os.close();
buffIn.close();

It is important to use storeFileStream() instead of storeFile(). Also, as the commenter suggests, you need to check the server’s return code and do proper error handling.

Related Problems and Solutions