File write

Put your problem here if it does not fit any of the other categories.

File write

Postby aDeveloper » Mon Dec 31, 2007 11:12 pm

HI,

How to read from the stream and write it to a file instead writing byte by byte. Here is code

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2. FileOutputStream fos = new FileOutputStream(bkpFile);
  3.  
  4.  
  5.  
  6. InputStream inStrm = post.getResponseBodyAsStream();
  7.  
  8.  
  9.  
  10. int bytesRead = inStrm.read(byteData);
  11.  
  12.  
  13.  
  14. int totalBytes = 0;
  15.  
  16.  
  17.  
  18. while(bytesRead > 0)
  19.  
  20. {
  21.  
  22. totalBytes++ ;
  23.  
  24. fos.write(byteData) ;
  25.  
  26. bytesRead = inStrm.read(byteData);
  27.  
  28. }
  29.  
  30.  
  31.  
  32.  
  33.  
  34. fos.close();
Parsed in 0.031 seconds, using GeSHi 1.0.8.4



Here, post.available() returns 0,

Please help.
Regards,
-aDeveloper
aDeveloper
Freshman
Freshman
 
Posts: 3
Joined: Mon Dec 31, 2007 11:00 pm

Top

Postby jeremian » Tue Jan 01, 2008 1:26 pm

Hi,

you have to declare byteData as an array. For example:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. byte[] byteData = new byte[4096]; // <------
  2.  
  3. FileOutputStream fos = new FileOutputStream(bkpFile);
  4.  
  5.  
  6.  
  7. InputStream inStrm = post.getResponseBodyAsStream();
  8.  
  9.  
  10.  
  11. int bytesRead = inStrm.read(byteData);
  12.  
  13.  
  14.  
  15. int totalBytes = 0;
  16.  
  17.  
  18.  
  19. while(bytesRead > 0)
  20.  
  21. {
  22.  
  23. <span style="font-weight: bold">totalBytes += bytesRead;</span>
  24.  
  25. fos.write(byteData) ;
  26.  
  27. bytesRead = inStrm.read(byteData);
  28.  
  29. }
  30.  
  31.  
  32.  
  33.  
  34.  
  35. fos.close();
Parsed in 0.031 seconds, using GeSHi 1.0.8.4



Moreover, it's good to use BufferedOutputStream/BufferedInputStream to minimize disk usage.

Regards,
jeremian.
jeremian
Freshman
Freshman
 
Posts: 6
Joined: Thu Dec 13, 2007 11:28 pm

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 19 guests