by ryderster » Fri Feb 13, 2009 4:16 pm
Hi lads,
below is an example that works for me. The function takes ina url of a mp3 file.
it then stores the file on the emulator in the /data/data/yourapplication/
Not sure if is the best way to do it but it works for me
private String getMp3File(String path) throws IOException {
URL url = new URL(path);
URLConnection cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
String contentType = cn.getContentType();
int contentLength = cn.getContentLength();
if (stream == null)
throw new RuntimeException("stream is null");
InputStream in = new BufferedInputStream(stream);
byte[] data = new byte[contentLength];
int bytesRead = 0;
int offset = 0;
while (offset < contentLength) {
bytesRead = in.read(data, offset, data.length - offset);
if (bytesRead == -1)
break;
offset += bytesRead;
}
in.close();
if (offset != contentLength) {
throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
}
String filename = url.getFile().toString();
filename=filename.substring(filename.lastIndexOf('/') + 1);
FileOutputStream out = openFileOutput(filename, MODE_WORLD_READABLE);
out.write(data);
out.flush();
out.close();
cn=null;
return filename;
}