簡體   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