Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.InputStream;
import java.io.OutputStream;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.content.Context;

import android.os.Environment;

import android.util.Log;

public class Main {
    private final static String TAG = "ZambelzUtility";

    /**
     * 
     * @param context
     * @param backupFolder
     * @param db_name
     * @return
     */
    public static boolean backupDB(Context context, String backupFolder, String db_name) {
        boolean result = false;

        try {
            String current_date = DateToString(GetToday(), "dd-MM-yyyy");

            File data = Environment.getDataDirectory();
            File sdcard = new File(Environment.getExternalStorageDirectory(), backupFolder + "/");
            sdcard.mkdirs();

            if (sdcard.canWrite()) {
                String currentDBPath = "//data//" + context.getPackageName() + "//databases//" + db_name + "";
                String backupDBPath = "backup_" + db_name + "_" + current_date + ".db";

                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sdcard, backupDBPath);

                if (currentDB.exists()) {
                    InputStream input = new FileInputStream(currentDB);
                    OutputStream output = new FileOutputStream(backupDB);

                    byte[] buffer = new byte[1024];
                    int length;

                    while ((length = input.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }

                    output.flush();
                    output.close();
                    input.close();

                    result = true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

        return result;
    }

    /**
     * convert from 'Date' format into 'String' format
     * @param Date dt
     * @param String Format
     * @return
     */
    public static String DateToString(Date dt, String Format) {
        SimpleDateFormat df = new SimpleDateFormat(Format);
        return df.format(dt);
    }

    /**
     * get current date
     * @return
     */
    public static Date GetToday() {
        return Calendar.getInstance().getTime();
    }
}