[英]Java: How to extract matching lines from a large text file fast?
雖然知道有很多,一般提供的解決方案,以我的問題,我仍然不滿意,他們在我的特殊情況所需要的運行環境。
考慮一個FASTA格式的35G大文本文件 ,如下所示:
>Protein_1 So nice and cute little fella MTTKKCLQKFHLESLGKLGDSFLKYAISIQLFKSYENHYEGLPSIKKNKIISNAALFKLG YARKILRFIRNEPFDLKVGLIPSDNSQAYNFGKEFLMPSVKMCSRVK* >Protein_2 Fancy incredible description of its function MADDSKFCFFLVSTFLLLAVVVNVTLAANYVPGDDILLNCGGPDNLPDADGRKWGTDIGS […] etc.
我需要提取>
專用線。
使用grep '>' proteins.fasta > protein_descriptions.txt
只需幾分鍾。
但是現在使用Java 7已經運行了90分鍾以上:
public static void main(String[] args) throws Exception {
BufferedReader fastaIn = new BufferedReader(new FileReader(args[0]));
List<String> l = new ArrayList<String>();
String str;
while ((str = fastaIn.readLine()) != null) {
if (str.startsWith(">")) {
l.append(str);
}
}
fastaIn.close();
// …
}
有誰知道如何加快grep
性能?
您的幫助將不勝感激。 干杯!
如果立即將其寫入輸出文件,而不是在內存中累積對象,則它將提高性能(並且無論如何都將更像是使用grep所做的那樣)。
...
BufferedWriter fastaOut = new BufferedWriter(new FileWriter(args[1]));
...
while ((str = fastaIn.readLine()) != null) {
if (str.startsWith(">")) {
fastaOut.write(str);
fastaOut.newLine();
}
}
...
fastaOut.close();
biojava.org提供了Fasta閱讀器。 為了讀取大文件,您必須考慮使用SeekableByteChannell和ByteBuffers。 biojava庫使用字節緩沖區。
您可能使用多個線程可以大大加快此過程。 如果文件的長度為X個字節,並且有n個線程,則以X / n的間隔啟動每個線程,並讀取X / n個字節。 您將需要同步ArrayList以確保正確添加結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.