简体   繁体   English

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

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

I have a large file of 45MB, and suppose the memory available to me is limited and I want to read 5MB first and so on. 我有一个45MB的大文件,并且假设可用内存有限,我想先读取5MB,依此类推。

I need to do this using Java. 我需要使用Java做到这一点。 Somebody please help me out. 有人请帮帮我。

Thanks in advance!! 提前致谢!!

I think you can just use basic byte streams for this. 我认为您可以为此使用基本字节流。 Check out http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html 查看http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html

I'd use the read(byte[] b) method of a FileInputStream class which 'Reads up to b.length bytes of data from this input stream into an array of bytes' 我将使用FileInputStream类的read(byte [] b)方法,该方法“从此输入流中将b.length个字节的数据读取到字节数组中”

read(byte[] b, int off, int len) method would also allow you to do this with an offset for previously read data. read(byte [] b,int off,int len)方法还将允许您使用以前读取的数据的偏移量来执行此操作。

Following code would read 5000 bytes (5MB) from the file. 以下代码将从文件读取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