如何使用Java将RAW数据写入文件?例如,与: nc -l 8000 > 相同捕获.raw
在 TCP 中,我从 IP 摄像机接收 RAW 媒体流。根据那里的建议,我需要将其写为文件。然后我可以用 VLC 等媒体播放器播放它。
但是当我将其写入文件并使用媒体播放器播放时,它永远不会播放损坏。
比较原始文件后,我发现我的 Java 用了错误的字符。并且示例文件显示不同。我该如何解决此类文件写入问题,以下是我的编写方式:
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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应将
Readers
、Writers
和Strings
用于二进制数据。坚持使用InputStreams
和OutputStreams
。即,更改
BufferedWriter
->BufferedOutputStream
,FileWriter
->FileOutputStream
String
,只需使用byte[]
。如果您正在处理套接字,我必须建议您查看 NIO 包 不过。
You shouldn't use
Readers
,Writers
andStrings
for binary data. Stick withInputStreams
andOutputStreams
.I.e., change
BufferedWriter
->BufferedOutputStream
,FileWriter
->FileOutputStream
String
, just use abyte[]
.If you're dealing with sockets, I must advice you to look into the NIO package though.
你做得对......至少直到你将
byte[]
转换为String
的部分:只有当你的
byte[]
首先表示文本数据!它没有!每当您处理二进制数据或实际上并不关心数据代表什么时,您必须避免使用
String
/< code>Reader/Writer
来处理该数据。相反,请使用byte[]
/InputStream
/OutputStream
。另外,您必须循环地从套接字读取数据,因为没有什么可以保证您已经读取了所有内容:
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
/Writer
to 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:
您的写入方式将输出文件的最大大小限制为 1024 字节。尝试循环:
The way you have it written limits the output file to a maximum size of 1024 bytes. Try a loop: