我正在开发一个应用程序,我想从互联网上下载图像并将其保存到每个手机的照片库中。请给我一些建议。 谢谢,
答案 0 :(得分:1)
private void downloadImage(String folder, String photoName, String url) throws IOException
{
byte[] rawImg = null;
try
{
String imageData = getDataFromUrl(url);
rawImg = imageData.getBytes();
putPhotoToPhone(rawImg, folder, photoName);
}
catch(Exception e1) {
e1.printStackTrace();
}
}
private String getDataFromUrl(String url) throws IOException {
StringBuffer b = new StringBuffer();
InputStream is = null;
HttpConnection c = null;
long len = 0 ;
int ch = 0;
c = (HttpConnection)Connector.open(url);
is = c.openInputStream();
len = c.getLength();
if( len != -1)
{
for(int i =0 ; i < len ; i++ )
{
if((ch = is.read()) != -1)
{
b.append((char) ch);
}
}
}
else
{
while ((ch = is.read()) != -1)
{
len = is.available() ;
b.append((char)ch);
}
}
is.close();
c.close();
return b.toString();
}
private void putPhotoToPhone(byte[] rawImg, String photoDir, String imageName)
{
FileConnection fcDir, fcFile;
String pRoot = "Phone:/";
OutputStream os;
if (rawImg != null)
{
try
{
fcDir = (FileConnection) Connector.open("file:///"+pRoot+photoDir+"/", Connector.READ_WRITE);
if (!fcDir.exists())
fcDir.mkdir();
fcFile = (FileConnection) Connector.open("file:///"+pRoot+photoDir+"/"+imageName, Connector.READ_WRITE);
if (fcFile.exists())
fcFile.delete();
fcFile.create();
os = fcFile.openOutputStream();
os.write(rawImg);
os.flush();
os.close();
fcFile.close();
fcDir.close();
}
catch (Exception e) {}
}
}