BufferedInputStream.read(byte[]) Causes problems. Anyone have this problem before?
I've written a Java program that downloads audio files for me and I'm using BufferedInputStream. The read() function works fine but is really slow so I've tried using the overloaded version using byte[].
For some reason, the audio becomes lossy and strange after download. I'm not totally sure what I'm doing wrong so any help is appreciated! Here's the simplified, sloppy version of the code.
BufferedInputStream bin = new BufferedInputStream((new URL(url)).openConnection().getInputStream());
File file = new File(fileName);
FileOutputStream fop = new FileOutputStream(file);
int r开发者_如何转开发d = bin.read();
while(rd != -1)
{
fop.write(rd);
rd = bin.read();
}
Remember that when you read in bytes, read will return the number of bytes that were actually received. You need to pass that count to write because you may have extraneous data in your byte array. This is especially true in the last block of data.
the read method you're using actually returns a byte inside that int it returns, which means that only 8 bits of the 32 bits in your variable "rd" are actually used.
the method write states that it takes an int as argument, but writes "the specified byte to this file output stream." which means you should be ok.. but i'm thinking you're not D:
try using the read-method that takes a byte-array as argument instead, and then write that byte-array to your output stream.
however, be aware that this other read-method, the one that takes a byte array as argument, it also returns an int. but unlike the method you're using in your example (which returns one of the bytes from the input data), this other read-method returns the number of bytes that was read. this isn't necessary the number of bytes that your byte array can contain. in that case, you must make sure that you don't write more bytes to the output stream than was actually read from that last read operation.
精彩评论