2011-10-04 41 views
1

在TCP中,我從RAW攝像機接收來自IP攝像機的媒體流。據此建議,我需要將其作爲文件編寫。然後我可以用VLC等媒體播放器播放它。如何使用Java將RAW數據寫入文件?例如:nc -l 8000> capture.raw

但是,當我寫這篇文章到一個文件中,並與媒體播放器播放它從來不玩損壞。

比較原始文件後,我看到我的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); 
} 

回答

2

你這樣做是正確的......至少要等到部分,你把你的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(); 
+0

我相信它應該是: 「out.write(BUF,0,bytes_read緩存);」,而不是 「out.write(數據,0,bytes_read緩存);」 – user1723095

4

你不應該使用ReadersWritersStrings二進制數據。堅持與InputStreamsOutputStreams

即,改變

  • BufferedWriter - >BufferedOutputStream
  • FileWriter - >FileOutputStream
  • 和替代String,只需使用一個byte[]

如果您正在處理套接字,我必須建議您查看NIO package

+1

我第二個'看看NIO'的概念。它可能是一個簡單問題的過於複雜的解決方案,但是它可能不是。 – claymore1977

1

你有它編寫方式限制了輸出文件的最大尺寸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); 
    }