繁体   English   中英

如何从Java文件中读取特定数量的数据

[英]how to read particular amount of data from a file in java

我有一个45MB的大文件,并且假设可用内存有限,我想先读取5MB,依此类推。

我需要使用Java做到这一点。 有人请帮帮我。

提前致谢!!

我认为您可以为此使用基本字节流。 查看http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html

我将使用FileInputStream类的read(byte [] b)方法,该方法“从此输入流中将b.length个字节的数据读取到字节数组中”

read(byte [] b,int off,int len)方法还将允许您使用以前读取的数据的偏移量来执行此操作。

以下代码将从文件读取5000字节(5MB)。

byte[] bytes = new byte[5000]; 
    DataInputStream dis = new DataInputStream(new FileInputStream(file)); 
      int read = 0;
      int numRead = 0;
      while (read < bytes.length && (numRead=dis.read(bytes, read, bytes.length-read)) >= 0) {
        read = read + numRead;
      }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM