FileHandler.java

/*
 * Copyright © 2012 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners.
 * See LICENSE.TXT for license information.
 */

package com.nokia.example.paint.helpers;

import com.nokia.example.paint.Main;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Image;
import java.util.Timer;
import java.util.TimerTask;

public class FileHandler {

    public FileHandler() {
    }

    public static void saveImageToFile(final String filename, final Image image) {
        new Thread() {

            public void run() {

                if (filename.length() > 0) {

                    FileConnection con = null;
                    OutputStream out = null;
                    try {
                        con = (FileConnection) Connector.open(
                                System.getProperty("fileconn.dir.photos") + filename + ".bmp");
                        if (con != null) {
                            Main.getInstance().showProgressAlert();
                            Main.getInstance().updateProgressText("Saving...");
                            if (con.exists()) {
                                con.delete();
                            }
                            con.create();
                            out = con.openOutputStream();
                            BMPEncoder enc = new BMPEncoder(image);
                            enc.writeImageToFile(out);
                            Main.getInstance().updateProgressText("Image saved");
                        }
                    }
                    catch (Exception e) {
                        Main.getInstance().showError("Unable to save.");
                    }
                    finally {
                        try {
                            if (out != null) {
                                out.close();
                            }
                            if (con != null) {
                                con.close();
                            }
                        }
                        catch (IOException io) {
                        }
                    }

                    Timer timer = new Timer();
                    TimerTask closeDialog = new TimerTask() {

                        public void run() {
                            Main.getInstance().hideProgressAlert();
                        }
                    };
                    timer.schedule(closeDialog, 1600);
                }
                else {
                    Main.getInstance().showError("Please give filename.");
                }
            }
        }.start();
    }
}