【发布时间】:2013-10-26 13:31:57
【问题描述】:
我有一些 Java 代码可以按照预期的方式运行,但它需要一些时间 - 几秒钟 - 即使作业只是循环遍历数组。
输入文件是一个 Fasta 文件,如下图所示。我正在使用的文件是 2.9Mo,还有一些其他的 Fasta 文件最多可以占用 20Mo。
在代码中,我试图通过三组循环遍历它,例如:AGC TTT TCA ......基地。示例:
AGC - Ser / CUG Leu / ...等
那么代码有什么问题?有什么办法可以做得更好吗?有什么优化吗?遍历整个 String 需要一些时间,可能只需几秒钟,但需要找到更好的方法。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class fasta {
public static void main(String[] args) throws IOException {
File fastaFile;
FileReader fastaReader;
BufferedReader fastaBuffer = null;
StringBuilder fastaString = new StringBuilder();
try {
fastaFile = new File("res/NC_017108.fna");
fastaReader = new FileReader(fastaFile);
fastaBuffer = new BufferedReader(fastaReader);
String fastaDescription = fastaBuffer.readLine();
String line = fastaBuffer.readLine();
while (line != null) {
fastaString.append(line);
line = fastaBuffer.readLine();
}
System.out.println(fastaDescription);
System.out.println();
String currentFastaAcid;
for (int i = 0; i < fastaString.length(); i+=3) {
currentFastaAcid = fastaString.toString().substring(i, i + 3);
System.out.println(currentFastaAcid);
}
} catch (NullPointerException e) {
System.out.println(e.getMessage());
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
fastaBuffer.close();
}
}
}
【问题讨论】:
-
我不知道,为什么它花费的时间比预期的要长,我唯一可以提到的是 StringBuilder 内置了“substring”方法,所以你可以避免总是创建一个字符串( toString()) 在取出子序列之前。
标签: java string for-loop bioinformatics fasta