java讀取大文件 超大文件的幾種方法


java 讀取一個巨大的文本文件既能保證內存不溢出又能保證性能  
 
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
 
public class ReadBig {
public static String fff = "C:\\mq\\read\\from.xml";
 
public static void main1(String[] args) throws Exception {
 
  final int BUFFER_SIZE = 0x300000;// 緩沖區大小為3M
 
  File f = new File(fff);
 
  /**
   * 
   * map(FileChannel.MapMode mode,long position, long size)
   * 
   * mode - 根據是按只讀、讀取/寫入或專用(寫入時拷貝)來映射文件,分別為 FileChannel.MapMode 類中所定義的
   * READ_ONLY、READ_WRITE 或 PRIVATE 之一
   * 
   * position - 文件中的位置,映射區域從此位置開始;必須為非負數
   * 
   * size - 要映射的區域大小;必須為非負數且不大於 Integer.MAX_VALUE
   * 
   * 所以若想讀取文件后半部分內容,如例子所寫;若想讀取文本后1/8內容,需要這樣寫map(FileChannel.MapMode.READ_ONLY,
   * f.length()*7/8,f.length()/8)
   * 
   * 想讀取文件所有內容,需要這樣寫map(FileChannel.MapMode.READ_ONLY, 0,f.length())
   * 
   */
 
  MappedByteBuffer inputBuffer = new RandomAccessFile(f, "r")
    .getChannel().map(FileChannel.MapMode.READ_ONLY,
      f.length() / 2, f.length() / 2);
 
  byte[] dst = new byte[BUFFER_SIZE];// 每次讀出3M的內容
 
  long start = System.currentTimeMillis();
 
  for (int offset = 0; offset < inputBuffer.capacity(); offset += BUFFER_SIZE) {
 
   if (inputBuffer.capacity() - offset >= BUFFER_SIZE) {
 
    for (int i = 0; i < BUFFER_SIZE; i++)
 
     dst[i] = inputBuffer.get(offset + i);
 
   } else {
 
    for (int i = 0; i < inputBuffer.capacity() - offset; i++)
 
     dst[i] = inputBuffer.get(offset + i);
 
   }
 
   int length = (inputBuffer.capacity() % BUFFER_SIZE == 0) ? BUFFER_SIZE
     : inputBuffer.capacity() % BUFFER_SIZE;
 
   System.out.println(new String(dst, 0, length));// new
   // String(dst,0,length)這樣可以取出緩存保存的字符串,可以對其進行操作
 
  }
 
  long end = System.currentTimeMillis();
 
  System.out.println("讀取文件文件一半內容花費:" + (end - start) + "毫秒");
 
}
 
public static void main2(String[] args) throws Exception {
  int bufSize = 1024;
  byte[] bs = new byte[bufSize];
  ByteBuffer byteBuf = ByteBuffer.allocate(1024);
  FileChannel channel = new RandomAccessFile(fff, "r").getChannel();
  while (channel.read(byteBuf) != -1) {
   int size = byteBuf.position();
   byteBuf.rewind();
   byteBuf.get(bs); // 把文件當字符串處理,直接打印做為一個例子。
   System.out.print(new String(bs, 0, size));
   byteBuf.clear();
  }
 
}
 
public static void main(String[] args) throws Exception {
  BufferedReader br = new BufferedReader(new FileReader(fff));
  String line = null;
  while ((line = br.readLine()) != null) {
   System.out.println(line);
  }
}
 
public static void main(String[] args) throws Exception {
    int bufSize = 1024;
    byte[] bs = new byte[bufSize];
    ByteBuffer byteBuf = ByteBuffer.allocate(1024);
    FileChannel channel = new RandomAccessFile("d:\\filename","r").getChannel();
    while(channel.read(byteBuf) != -1) {
      int size = byteBuf.position();
      byteBuf.rewind();
      byteBuf.get(bs);
      // 把文件當字符串處理,直接打印做為一個例子。
      System.out.print(new String(bs, 0, size));
      byteBuf.clear();
    }
  }
 
}
 
 
 
 
 
 
 
java 讀取大容量文件,內存溢出?怎么按幾行讀取,讀取多次
 import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;
 
public class TestPrint {
public static void main(String[] args) throws IOException {
String path = "你要讀的文件的路徑";
RandomAccessFile br=new RandomAccessFile(path,"rw");//這里rw看你了。要是之都就只寫r
String str = null, app = null;
int i=0;
while ((str = br.readLine()) != null) {
i++;
app=app+str;
if(i>=100){//假設讀取100行
i=0;
// 這里你先對這100行操作,然后繼續讀
app=null;
}
}
br.close();
}
 
}
 
 
 
 
 
當逐行讀寫大於2G的文本文件時推薦使用以下代碼
void largeFileIO(String inputFile, String outputFile) {
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(inputFile)));
            BufferedReader in = new BufferedReader(new InputStreamReader(bis, "utf-8"), 10 * 1024 * 1024);//10M緩存
            FileWriter fw = new FileWriter(outputFile);
            while (in.ready()) {
                String line = in.readLine();
                fw.append(line + " ");
            }
            in.close();
            fw.flush();
            fw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
 
 
 
 
 
 
 
jdk本身就支持超大文件的讀寫。
 
網上的文章基本分為兩大類,一類是使用BufferedReader類讀寫超大文件;另一類是使用RandomAccessFile類讀取,經過比較,最后使用了前一種方式進行超大文件的讀取,下面是相關代碼,其實很簡單
 
-------------------------------------------------------------------
 
File file = new File(filepath);   
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));    
BufferedReader reader = new BufferedReader(new InputStreamReader(fis,"utf-8"),5*1024*1024);// 用5M的緩沖讀取文本文件  
  
String line = "";
while((line = reader.readLine()) != null){
//TODO: write your business
}
---------------------------------------------------------------------
 
注意代碼,在實例化BufferedReader時,增加一個分配緩存的參數即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM