java - Writing image not working properly using BufferedOutputStream -
iam reading , writing image file in java.the file can of type used buffered reader , writer while writing image not written properly.the image scattered.
bufferedreader bufferedreader = null; bufferedoutputstream bufferedwriter = null; if(!(dto.getinputstream() == null)){ try { bufferedreader = new bufferedreader(new inputstreamreader(dto.getinputstream())); fileoutputstream writer = new fileoutputstream(new file(webinflocation.getwebinfpath()+constantifc.resourcepath+dto.getfilename()+dto.getdocumentcode()+"_"+dto.getversion()+1+"."+dto.getformatname())); bufferedwriter = new bufferedoutputstream(writer); int value; while((value = bufferedreader.read()) != -1){ bufferedwriter.write(value); } } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } { try { if (bufferedreader != null) { bufferedreader.close(); } if (bufferedwriter != null) { bufferedwriter.close(); } dto.getinputstream().close(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } }
this problem:
bufferedreader = new bufferedreader(new inputstreamreader(dto.getinputstream()));
you're using inputstreamreader
, means it's reading binary data text. don't that. outputstream
fine, it's input handling broken.
you should use inputstream
, or possibly bufferedinputstream
, ideally reading blocks of data @ time instead of single byte:
byte[] buffer = new byte[8192]; // try read 8k @ time int bytesread; while ((bytesread = input.read(buffer)) > 0) { output.write(buffer, 0, bytesread); }
there various libraries you, e.g. guava can use bytesstreams.copy
.
also note if you're java 7, code can much simpler using try-with-resources statement perform closing you. example:
try (inputstream input = dto.getinputstream(); outputstream output = files.newoutputstream(...)) { bytesstreams.copy(input, output); }
use path
api specify path file - i'd suggest using call string.format
instead of concatenation, too.
Comments
Post a Comment