![](/img/trans.png)
[英]How to read a file (e.g txt file) from another java package withouth specifying the absolute path?
[英]How to write RAW data to a file using Java? e.g same as: nc -l 8000 > capture.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);
}
您不應該將Readers
, Writers
和Strings
用於二進制數據。 堅持使用InputStreams
和OutputStreams
。
即改變
BufferedWriter
> BufferedOutputStream
, FileWriter
> FileOutputStream
String
,只需使用byte[]
。 如果要處理套接字,我必須建議您研究一下NIO軟件包 。
您做對了...至少直到將byte[]
轉換為String
那一部分為止:
僅當您的byte[]
表示文本數據時,該步驟才有意義! 它不 !
每當處理二進制數據或實際上不關心數據表示什么時,都必須避免使用String
/ Reader
/ Writer
來處理該數據。 而是使用 byte[]
/ InputStream
/ OutputStream
。
另外,您必須循環讀取套接字,因為沒有什么可以保證您已讀取所有內容:
byte[] buf=new byte[1024];
int bytes_read;
OutputStream out = new FileOutputStream("capture.ogg", true);
InputStream in = sock.getInputStream();
while ((bytes_read = in.read(buf)) != -1) {
out.write(buf, 0, bytes_read);
}
out.close();
編寫方式將輸出文件限制為最大1024個字節。 嘗試循環:
try {
byte[] buf = new byte[1024];
int bytes_read = 0;
InputStream in = sock.getInputStream();
FileOutputStream out = new FileOutputStream(new File("capture.ogg"));
do {
bytes_read = in.read(buf, 0, buf.length);
System.out.println("Just Read: " + bytes_read + " bytes");
if (bytes_read < 0) {
/* Handle EOF however you want */
}
if (bytes_read > 0)
out.write(buf, 0, bytes_read);
} while (bytes_read >= 0);
out.close();
} catch (IOException e) {
e.printStackTrace(System.err);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.