In TCP i am receiving media stream from an IP camera as RAW. According to there advise, i need to write that as file. And then i can play it with media player such as VLC.
But when i write this to a file, and play with media players it never play corrupted.
After comparing the original file i see my Java writing it in wrong characters. And there sample file shows different. What or how do i fix such file writing issue, here is how i am writing it:
byte[] buf=new byte[1024];
int bytes_read = 0;
try {
bytes_read = sock.getInputStream().read(buf, 0, buf.length);
String data = new String(buf, 0, bytes_read);
System.err.println("DATA: " + bytes_read + " bytes, data=" +data);
BufferedWriter out = new BufferedWriter(
new FileWriter("capture.ogg", true));
out.write(data);
out.close();
} catch (IOException e) {
e.printStackTrace(System.err);
}
You’re doing it right… at least until the part where you turn your
byte[]into aString:That step only really makes sense if your
byte[]represents textual data in the first place! Which it doesn’t!Whenever you handle binary data or don’t actually care what the data represents you must avoid using
String/Reader/Writerto handle that data. Instead do usebyte[]/InputStream/OutputStream.Also, you must read from the socket in a loop, because nothing guarantees that you’ve read everything: