Home

Java code to save file on FTP server

import org.apache.commons.net.ftp.FTPClient;  

    @Override
    public void backupToFTP() {
       
        FTPClient client = new FTPClient();
        FileInputStream fis = null;

        try {
            client.connect(host);
            client.login(FTPUsername, FTPPassword);
           
            fis = new FileInputStream(filePath);
           
            client.storeFile(newFileName, fis);
            client.logout();
           
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                client.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
       
    }

Java code to backup MySQL database

The command line syntax to backup a MySQL database is:


mysqldump -u [username] -p [password] [databasename] > [backupfile.sql]


e.g.: mysqldump -u root -p admin testDB > testDB.sql


http://www.devshed.com/c/a/MySQL/Backing-up-and-restoring-your-MySQL-Database/


Java code:


String[] command = new String[] { "mysqldump", "--user=" + mySQLUsername,

"--password=" + mySQLPassword, "--databases", schema, "-r",

backupPath + "/" + filename};


Runtime runtime = Runtime.getRuntime();

Process process = null;

try {

process = runtime.exec(command);

} catch (IOException e) {

e.printStackTrace();

}

try {

process.waitFor();

} catch (InterruptedException e) {

e.printStackTrace();

}



schema – database name

backupPath – path where you will make the .sql file

filename – name of the .sql file



Accessing newly created database right away:

Creating the sql script takes some time. If you access the file right away and the physical file hasn't been created yet you will get a FileNotFoundException.


Solution:

Make the current thread wait until the process running the exec method finishes.

Welcome to the Scorpion Software .ro Blog

A Java technologies troubleshooting knowledge database

Scorpion Software is a youthful web development company based in Cluj-Napoca, Romania. Our expertise is focused towards delivering Java enterprise-ready web solutions by means of open-source technologies, an agile approach and innovation.

Read more...