简体   繁体   中英

Saving huge file in a string JAVA

i'm trying to read a FASTA file into a string in java. My code works fine with small files, but when I choose a real FASTA file which includes 5 million chars, so I can use this string, the program get stucked . get stucked= i see no output, and the program becomes with black screen.

    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;
}

Try to use a StringBuilder to process big loads of text data:

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();

}

I would try to use BufferedReader to read the file, something like this:

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;
}

And also concatenate with StringBuilder like davidbuzatto said.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM