Thursday, October 1, 2009

Download image or any file from URL to specific file path-BlackBerry Development

Give url and downloaad location very simple

public boolean downloadImage(String url,String path)
{
    if(saveImage(getImage(url),path))
    {
    return true;
    }
    else
    {
        return false;
    }
}
public static String getImage(String url)
{
String response = "";
try {
HttpConnection conn = (HttpConnection)Connector.open(url, Connector.READ_WRITE);
InputStream input =conn.openInputStream();
byte[] data = new byte[256];
int len = 0;
StringBuffer raw = new StringBuffer();
while( -1 != (len = input.read(data)))
{
raw.append(new String(data, 0, len));
}
response = raw.toString();
input.close();
} catch(Exception e)
{
Dialog.alert("Error");
}
return response;
}
public boolean saveImage(String txt,String path1)
    {
        boolean str = false;
        try {
            FileConnection fc1 = (FileConnection)Connector.open(path1, Connector.READ_WRITE);
            if(!fc1.exists())
            {
            fc1.create();
            }
            fc1.setWritable(true);
                byte[] size1=txt.getBytes();
                OutputStream os=fc1.openOutputStream();
                os.write(size1);
                os.close();
                return true;        
        }
        catch (Exception ioe)
        {
            System.out.println("File Sys Error"+ioe.getMessage());
        }
        return str;
    }

No comments:

Post a Comment