BufferedReader偏移到文件内容中

时间:2014-06-17 17:26:34

标签: java bufferedreader

我想获取文件的字符,我知道前128个字节是垃圾,接下来的4个字节给我重要的细节。

目前我这样做:

    br = new BufferedReader(new FileReader(path));
    char[] cbuf = new char[133]; 
    br.read(cbuf, 0, 132);
    String importantDetails = "";
    for(int i=128;i<132;i++) importantDetails += cbuf[i];

但我觉得这是一种非常丑陋的方式,首先我尝试过:

    String importantDetails = cbuf.toString().substring(128); 

给出错误(字符串索引超出范围:-118)。 只有cbuf.toString()打印[C@d70c109

在java中有更好的方法吗?

我觉得文件中应该有一个偏移量(因为read(cbuf [],offset,length)的偏移量是cbuf []中的偏移量而不是要读取的文件中的偏移量。

1 个答案:

答案 0 :(得分:1)

您可以使用RandomAccessFile来做到这一点。代码:

  RandomAccessFile file = new RandomAccessFile(path, "r");
  file.seek(128); // Sets the file-pointer offset
  byte[] b = new byte[4];
  file.readFully(b);

应该做你想要的(减去所有错误检查)。

See the javadoc for more details :