views:

188

answers:

2

dear all, i want to read a mp3 file using java and want to download it in jsp,i want to return byte array or i can only return one byte at a time?.please suggest

+1  A: 

Just create a servlet class which reads the file into an InputStream using FileInputStream and write it to the OutputStream of the HttpServletResponse the usual Java IO way. Don't forget to set the HTTP Content-Length and Content-Type headers accordingly, else it will be sent with chunked encoding (which is a tad slower), or the browser won't know what to do with the information. Finally map this servlet on an url-pattern in web.xml and invoke it by URL wherein you pass the file identifier as request parameter or pathinfo. You can find here a basic example of such a servlet.

BalusC
thanks balusc,i want to no how can i download a large file i n a handset?(mobile).i m getting error on browser i m able to download a file but on mobile i m getting i m getting exception
sharma
Sorry, I can't parse your English. You need to be more clear and descriptive. Please, there are zillion kinds of errors, which one did you got?
BalusC
i m working on a wap project ,i want to download mp3 files when user presses an option using gprs.i m testing this application using opera browser which is used for(wap-wireless access protocol) ,there i m able to download a file using code u mentioned above.but now i m facing a major problem i m not able to download on mobile .may be slow network or speed.what can be the best soloution to make it work.please suggest. byte[] buffer = new byte[1024]intbyteRead = 0;while((byteReadfis.read(buffer)) !os.write(buffer, 0, byteRead);}i m using this code small sample.
sharma
Yes Ok, but which exception did you got? Exceptions tell something about the cause of the problem. You know, once the cause is *understood*, the solution is *obvious*.
BalusC
can i use nio with jsp for solving this problem?.mobile gives exception like-no request and my code stucks inside while.
sharma
Sounds like the HTTP `Content-Length` is missing. Show the HTTP resposne headers.
BalusC
A: 

You are simply describing serving a file across the web. It sounds like you are already using a servlet container like Tomcat. Why not just let Tomcat serve the file? No code needed and it will probably be done better and more efficiently than a custom solution.

Sean Owen