【问题标题】:How to write RAW data to a file using Java? e.g same as: nc -l 8000 > capture.raw如何使用 Java 将 RAW 数据写入文件?例如:nc -l 8000 > capture.raw
【发布时间】:2011-10-04 13:14:34
【问题描述】:

在 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);
}

【问题讨论】:

    标签: java linux file-io


    【解决方案1】:

    您不应将ReadersWritersStrings 用于二进制数据。坚持使用InputStreamsOutputStreams

    即改变

    • BufferedWriter -> BufferedOutputStream,
    • FileWriter -> FileOutputStream
    • 而不是String,只需使用byte[]

    如果您正在处理套接字,我必须建议您查看NIO package

    【讨论】:

    • 我支持“看看 NIO”的概念。它可能是一个简单问题的过于复杂的解决方案,但话又说回来,它可能不是。
    【解决方案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();
    

    【讨论】:

    • 我认为应该是:“out.write(buf, 0, bytes_read);”,而不是“out.write(data, 0, bytes_read);”
    【解决方案3】:

    您编写它的方式将输出文件的最大大小限制为 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);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多