You cannot allocate a 14MB byte array in memory. Your application has only access to 16MB maximum. To download a large file from the Web, simply read it little bit by little bit. For instance, instead of reading 16MB at once, download 16 or 32kB, write them to the outputstream, and keep looping until the end of the stream.
On Mon, Jan 26, 2009 at 9:00 PM, Mahesh Vaghela <[email protected]> wrote: > Hi Friends, > > I want to play an mp3 file as soon as my application starts. The mp3 file is > really large in size(approx 14 mb). > > So I am trying to download it from a webserver and than I want to store it > on sdcard. > > While doing so I am getting OutOfMemoryException. Can anybody please help > me? > > My code is as follows: > >>>>>>>>>>>>>>>> > > public MainClass() throws Exception > { > > URL u = new URL("http://----------"); > URLConnection uc = u.openConnection(); > String contentType = uc.getContentType(); > int contentLength = uc.getContentLength(); > > if(contentLength < Integer.MAX_VALUE) > { > > } > > if (contentType.startsWith("text/") || contentLength == -1) > { > throw new IOException("This is not a binary file."); > } > > InputStream raw = uc.getInputStream(); > > InputStream in = new BufferedInputStream(raw); > > > // Getting OutOfMemoryException here > > byte [] data=new byte[(int)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 = u.getFile().substring(filename.lastIndexOf('/') + 1); > > FileOutputStream out = new FileOutputStream("/sdcard/music.mp3"); > > out.write(data); > > out.flush(); > > out.close(); > > } > > > Mahesh > > > > > > > > -- Romain Guy Android framework engineer [email protected] Note: please don't send private questions to me, as I don't have time to provide private support. All such questions should be posted on public forums, where I and others can see and answer them --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Android Developers" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/android-developers?hl=en -~----------~----~----~----~------~----~------~--~---

