从同一个FileInputStream中读取字符串和二进制文件 [英] Reading Strings and Binary from the same FileInputStream

查看:199
本文介绍了从同一个FileInputStream中读取字符串和二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,在开始时包含一些纯文本,最后是二进制内容。二进制内容的大小由我读过的一条纯文本行确定。

I have a file that contains some amount of plain text at the start followed by binary content at the end. The size of the binary content is determined by some one of the plain text lines I read.

我使用的是 BufferedReader 读取各行,但是它没有公开引用读取字节数组的方法。对于 DataInputStream readUTF 并不一直读到行尾,而 readLine 方法已弃用。

I was using a BufferedReader to read the individual lines, however it exposes no methods to refer to read a byte array. The readUTF for a DataInputStream doesnt read all the way to the end of the line, and the readLine method is deprecated.

使用基础 FileInputStream 读取返回空字节阵列。关于如何解决此问题的任何建议?

Using the underlying FileInputStream to read returns empty byte arrays. Any suggestions on how to go about this?

private DOTDataInfo parseFile(InputStream stream) throws IOException{
DOTDataInfo info = new DOTDataInfo();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
int binSize = 0;
String line;
while((line = reader.readLine()) != null){
    if(line.length() == 0)
        break;
    DOTProperty prop = parseProperty(line);
    info.getProperties().add(prop);
    if(prop.getName().equals("ContentSize"))
        binSize = Integer.parseInt(prop.getValue());
}
byte[] content = new byte[binSize];
stream.read(content); //Its all empty now. If I use a DataInputStream instead, its got the values from the file
return info;
}


推荐答案

如果你真的有文件(而不是更难以寻找的东西,例如网络流)然后我建议这样的事情:

If you genuinely have a file (rather than something harder to seek in, e.g. a network stream) then I suggest something like this:


  • 将文件作为FileInputStream打开

  • 将它包装在InputStreamReader和BufferedReader中

  • 阅读文本,以便了解有多少内容

  • 关闭BufferedReader(将关闭将关闭FileInputStream的InputStreamReader)

  • 重新打开文件

  • 跳至(文件总长度 - 二进制内容长度)

  • 正常读取其余数据

  • Open the file as a FileInputStream
  • Wrap it in InputStreamReader and a BufferedReader
  • Read the text, so you can find out how much content there is
  • Close the BufferedReader (which will close the InputStreamReader which will close the FileInputStream)
  • Reopen the file
  • Skip to (total file length - binary content length)
  • Read the rest of the data as normal

你可以打电话 mark()在FileInputStream的开头,然后 reset() skip() 如果您想避免重新打开文件,请到正确的位置。 (我一直在寻找一个 InputStream.seek()但是我看不到一个 - 我记不起在Java之前想要它了,但它真的没有一个?Ick。)

You could just call mark() at the start of the FileInputStream and then reset() and skip() to get to the right place if you want to avoid reopening the file. (I was looking for an InputStream.seek() but I can't see one - I can't remember wanting it before in Java, but does it really not have one? Ick.)

这篇关于从同一个FileInputStream中读取字符串和二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆