2 package org.forester.io.writers;
5 import java.io.IOException;
9 import org.forester.sequence.MolecularSequence;
10 import org.forester.util.ForesterUtil;
12 public class SequenceWriter {
14 public static enum SEQ_FORMAT {
18 public static StringBuilder toFasta( final MolecularSequence seq, final int width ) {
19 return toFasta( seq.getIdentifier(), seq.getMolecularSequenceAsString(), width );
22 public static StringBuilder toFasta( final String name, final String mol_seq, final int width ) {
23 final StringBuilder sb = new StringBuilder();
26 sb.append( ForesterUtil.LINE_SEPARATOR );
27 if ( ( width < 1 ) || ( width >= mol_seq.length() ) ) {
31 final int lines = mol_seq.length() / width;
32 final int rest = mol_seq.length() - ( lines * width );
33 for( int i = 0; i < lines; ++i ) {
34 sb.append( mol_seq, i * width, ( i + 1 ) * width );
35 if ( i < ( lines - 1 ) ) {
36 sb.append( ForesterUtil.LINE_SEPARATOR );
40 sb.append( ForesterUtil.LINE_SEPARATOR );
41 sb.append( mol_seq, lines * width, mol_seq.length() );
47 public static void toFasta( final MolecularSequence seq, final Writer w, final int width ) throws IOException {
49 w.write( seq.getIdentifier() );
50 w.write( ForesterUtil.LINE_SEPARATOR );
51 if ( ( width < 1 ) || ( width >= seq.getLength() ) ) {
52 w.write( seq.getMolecularSequence() );
55 final int lines = seq.getLength() / width;
56 final int rest = seq.getLength() - ( lines * width );
57 for( int i = 0; i < lines; ++i ) {
58 w.write( seq.getMolecularSequence(), i * width, width );
59 if ( i < ( lines - 1 ) ) {
60 w.write( ForesterUtil.LINE_SEPARATOR );
64 w.write( ForesterUtil.LINE_SEPARATOR );
65 w.write( seq.getMolecularSequence(), lines * width, rest );
70 public static void writeSeqs( final List<MolecularSequence> seqs,
72 final SEQ_FORMAT format,
73 final int width ) throws IOException {
74 final Writer w = ForesterUtil.createBufferedWriter( file );
75 SequenceWriter.writeSeqs( seqs, w, format, width );
79 public static void writeSeqs( final List<MolecularSequence> seqs,
81 final SEQ_FORMAT format,
82 final int width ) throws IOException {
85 for( final MolecularSequence s : seqs ) {
86 toFasta( s, writer, width );
87 writer.write( ForesterUtil.LINE_SEPARATOR );
91 throw new RuntimeException( "unknown format " + format );