将巨大的文件保存在字符串JAVA中

时间:2018-04-11 17:48:24

标签: java file fasta

我正在尝试将FASTA文件读入java中的字符串。 我的代码适用于小文件,但是当我选择一个真正的FASTA文件时 其中包括500万个字符,所以我可以使用这个字符串,程序被卡住。卡住=我看不到输出,程序变成黑屏。

    public static String  ReadFastaFile(File file) throws IOException{  
    String seq="";
    try(Scanner scanner = new Scanner(new File(file.getPath()))) {
        while ( scanner.hasNextLine() ) {
            String line = scanner.nextLine();
            seq+=line;
            // process line here.
        }
    }
    return seq;
}

2 个答案:

答案 0 :(得分:1)

尝试使用StringBuilder处理大量文本数据:

public static String ReadFastaFile( File file ) throws IOException {

    StringBuilder seq = new StringBuilder();

    try( Scanner scanner = new Scanner( file ) ) {
        while ( scanner.hasNextLine() ) {
            String line = scanner.nextLine();
            seq.append( line );
            // process line here.
        }
    }

    return seq.toString();

}

答案 1 :(得分:0)

我会尝试使用BufferedReader来读取文件,如下所示:

public static String readFastaFile(File file) throws IOException {
    String seq="";
    try(BufferedReader br = new BufferedReader(new FileReader(file))) {
        String line;
        while ((line = br.readLine()) != null) {
            // process line here.
        }
    }
    return seq;
}

并且像davidbuzatto那样连接StringBuilder。

相关问题