【问题标题】:Reading bytes from a file从文件中读取字节
【发布时间】:2015-04-25 07:48:53
【问题描述】:

我正在使用下面的代码从“.264”文件中读取数据。

public static void main (String[] args) throws IOException
{

    BufferedReader br = null;try {
        String sCurrentLine;
        br = new BufferedReader(new InputStreamReader(new FileInputStream("test.264"),"ISO-8859-1"));
        StringBuffer stringBuffer = new StringBuffer();
        while ((sCurrentLine = br.readLine()) != null) {
            stringBuffer.append(sCurrentLine);      
        }
        String tempdec = new String(asciiToHex(stringBuffer.toString()));
        System.out.println(tempdec);
        String asciiEquivalent = hexToASCII(tempdec);
        BufferedWriter xx = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:/Users/Administrator/Desktop/yuvplayer-2.3/video dinalized/testret.264"),"ISO-8859-1"));
        xx.write(asciiEquivalent);
        xx.close();
    }catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}

在 HEX 编辑器中打开输入和输出文件会显示一些缺失值,例如0d(见附图)。

有什么办法解决这个问题吗?

【问题讨论】:

  • 您正在以文本模式读取二进制文件。在后者中,行由0d 字符 (CR) 分隔。
  • 那如何正确阅读呢?
  • 简短的回答是你将它作为字节流打开,这里有一个例子(它将字节存储在内存中,你需要将它们写入文件中): File to byte[] in Java。但除此之外,您应该明确您的需求,其他解决方案可能会得到更好的优化。
  • 请勿张贴文字图片。贴出文字。浪费您的时间和我们的带宽。
  • 从文件中读取所有字节的最简单方法是使用java.nio.file.Files.readAllBytes。这里还有一个关于发布屏幕截图的建议(如果你真的需要的话) - 选择一个窗口并按 alt-print 以仅捕获该窗口的屏幕截图。然后将其粘贴到油漆中并将其保存为 png(不是 jpg),然后通过 tinypng.com 发送。这样,您的图像将非常小。您发布的屏幕截图可能大小约为 40 kb,而且质量比您的 jpg 更好。但不要尝试将 jpg 转换为 png。这会产生一个巨大的图像。

标签: java fileinputstream inputstreamreader


【解决方案1】:

失去InputStreamReaderBufferedReader,只使用FileInputStream
没有字符编码,没有行尾,只有字节。
它的 Javadoc 页面是 here,这应该就是你所需要的。

如果您想一次读取整个文件,请提示:File.length(),如

File file = new File("test.264");
byte[] buf = new byte[(int)file.length()];
// Use buf in InputStream.read()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 2013-07-09
    • 1970-01-01
    相关资源
    最近更新 更多