[英]The best way to read a huge file (for example a very large text document)
我是java新手...在我當前的項目中,我需要讀取和寫入一個非常大的文本文件(1 GB - 5 GB)...首先我使用這個類: BufferedReader和BufferedWriter
public static String read(String dir) {
BufferedReader br;
String result = "", line;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(dir), "UTF-8"));
while ((line = br.readLine()) != null) {
result += line + "\n";
}
} catch (IOException ex) {
//do something
}
return result;
}
public static void write(String dir, String text) {
BufferedWriter bw;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dir), "UTF-8"));
bw.write("");
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) != '\n') {
bw.append(text.charAt(i));
} else {
bw.newLine();
}
}
bw.flush();
} catch (IOException ex) {
//do something
}
}
這個類非常好但不適用於巨大的文件......
然后我使用MappedByteBuffer作為read()
方法(我不知道如何使用這個類編寫文件):
public static String read(String dir) {
FileChannel fc;
String s = "";
try {
fc = new RandomAccessFile(dir, "r").getChannel();
MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
buffer.load();
buffer.force();
for (int i = 0; i < buffer.limit(); i++) {
s += (char) buffer.get();
} //I know the problem is here
buffer.clear();
inChannel.close();
} catch (IOException e) {
//do something
}
return s;
}
但仍然無法讀取大文件(超過30-40 MB),甚至NotePad比我的應用程序更快:))
另一個問題是我不知道如何以第二種方式改變編碼(例如“UTF-8”,“ANSI”,......)
那么大家好,請告訴我哪種讀寫laaaarge文件最好? 任何的想法?
result += line + "\n";
此行嘗試將整個文件內容保留在內存中。 嘗試按照這樣的方式處理每一行
while ((line = br.readLine()) != null) {
processLine( line ); // this may write it to another file.
}
至少,我建議改變
result += line + "\n";
到StringBuilder。
resultBldr.append(line).append("\n");
這樣可以避免在每一行上創建一個新的字符串對象 - 一個更大,更大,更大,更大的字符串對象!
此外,您絕對應該逐行將輸出寫入文件。 不要累積所有文本然后輸出它。
換句話說,在這種情況下,你完全分開read
和write
不推薦的功能。
認為字符串的每個連接都會創建一個新的字符串,所以,如果你讀取40 MB的大文件的每個字符並連接,你就會在read()
中創建類似40.000.000字符串的字符串。
嘗試使用StringBuffer
而不是String
,這對於這種情況是可以重復使用的。
在單次拍攝中讀取1GB到5GB范圍內的大尺寸文件總是一個壞主意。 將會有巨大的性能,您的應用程序將會放慢速度。
最好將這個巨大的文件分成更小的塊,然后按塊讀取它。 我想如果你開始用較小的塊讀取文件,你編寫的代碼將完美地工作。
您是否聽說過HDFS系統,Solr索引,apache hadoop框架,它們專門用於處理大量數據。 你可能想看看它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.