[英]How to read a file in chunks that is to large to be stored in memory
我正在練習,碰到一個問題,就是要從一個大到適合內存的文件中對數字進行排序。 我不知道該怎么做,所以我想嘗試一下。 我最終找到了外部排序,而我基本上只是想采用這個概念並編寫解決此問題的解決方案。 我正在練習的文本文件太大了,無法放入內存; 我只是想學習如何完成這樣的事情。 到目前為止,我正在從文件中讀取3個塊,每個塊500行,對這些塊進行排序,然后將結果塊寫入其自己的文件中。 盡管我不確定我的實現方式是如何實現外部排序過程的,但是這仍然有效:
import java.util.*;
import java.io.*;
public class ExternalSort{
public static void main(String[] args) {
File file = new File("Practice/lots_of_numbers.txt");
final int NUMBER_OF_CHUNKS = 3;
final int AMOUNT_PER_CHUNK = 500;
int numbers[][] = new int[NUMBER_OF_CHUNKS][AMOUNT_PER_CHUNK];
try{
Scanner scanner = new Scanner(file);
for(int i = 0; i < NUMBER_OF_CHUNKS; i++){
//Just creating a new file name for each chunk
StringBuilder sortedFileName = new StringBuilder().append("sortedFile").append(i).append(".txt");
for(int j = 0; j < AMOUNT_PER_CHUNK; j++){
numbers[i][j] = Integer.parseInt(scanner.nextLine());
}
Arrays.sort(numbers[i]);
saveResultsToFile(sortedFileName.toString(),numbers[i]);
}
scanner.close();
}catch(FileNotFoundException e){
System.out.println("Error: " + e);
}
}
public static void saveResultsToFile(String fileName, int arr[]){
try{
File file = new File(fileName);
PrintWriter printer = new PrintWriter(file);
for(int i : arr)
printer.println(i);
printer.close();
}catch(FileNotFoundException e){
System.out.println("Error :" + e);
}
}
}
我的問題是我應該如何將文件分解成塊? 我碰巧確切地知道我的文件有多少行文本,因為我創建了它,因此編寫此代碼很容易...但是問題實際上告訴了您文件的大小; 就像在內存中一樣,不是文件多少行文本。 我不確定如何將數據分解為“內存塊”(以及如何調整大小),而不是文本行。 另外,如果我的代碼有任何怪異,錯誤或錯誤的做法,請告訴我,因為我真的不知道我在做什么; 我只是想學習。 至於將排序后的文件重新合並在一起,我也不知道該怎么做,但是我有一個主意。 在尋求幫助之前,我想嘗試一下。 謝謝!
這是如何獲取我們要將文件拆分成的塊的大小的方法:
public static long chunkSize(File file){
//We don't want to create more that 1024 temp files for sorting
final long MAX_AMOUNT_OF_TEMP_FILES = 1024;
long fileSize = file.length();
long freeMemory = Runtime.getRuntime().freeMemory();
//We want to divide the file size by the maximum amount of temp files we will use for sorting
long chunkSize = fileSize / MAX_AMOUNT_OF_TEMP_FILES;
//If the block size is less than half the available memory, then we can stand to make the block size larger
if(chunkSize < freeMemory / 2)
chunkSize = freeMemory / 2;
else
System.out.println("Me may potentially run out of memory");
return chunkSize ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.