开发者社区> 问答> 正文

FileChinnel 读文件部分数据的问题:报错

@Test
public void test(){
FileInputStream inputStream = null;
    FileChannel inChannel = null;
I  OException exception = null;
    try {
        File file = new File("C://1301.txt");
        inputStream = new FileInputStream(file);
        inChannel = inputStream.getChannel();


        long position = 200;
        inChannel.position(position);
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        while(inChannel.size() > inChannel.position()){
            inChannel.read(buffer);
            buffer.flip();
            System.out.print(new String(buffer.array()));
            buffer.clear();
          }
    } catch (FileNotFoundException e) {
       e.printStackTrace();
       exception = e;
    } catch (IOException e) {
        e.printStackTrace();
        exception = e;
    } finally {
        try {
            if(inputStream != null){
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            if(exception == null){
                exception = e;
               }
        }
       if(exception != null){
        throw new RuntimeException(exception);
        }
    }

}

问题:描述信息,使用这个方法读取文件的时候,总是少了一部分数据。不知道错在那个地方。换了好几中方法都是不行。

测试的时候文件的大小一定要大于1.5M这样才能看出效果来。如果文件剩余部分小于1M的话。是没有问题的。

展开
收起
kun坤 2020-06-07 13:45:20 459 0
1 条回答
写回答
取消 提交回答
  • 不要用buffer.array(),用get。因为buffer.array()会多数据而不是少数据。你可以仔细观察一下。array()是吐出了1024(你设置的大小)的全部数据。里面包含了倒数第2次读取的部分信息,所以误让你认为读了一半。如果要用array()你要arrayOffset配合使用。

    while(inChannel.size() > inChannel.position()){
                    inChannel.read(buffer);
                    buffer.flip();
    
                    byte[] bytes=new byte[buffer.remaining()];
                    buffer.get(bytes);
                    System.out.print(new String(bytes));
                    buffer.clear();
                }
    2020-06-07 13:45:25
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载