2 package org.forester.io.writers;
5 import java.io.IOException;
9 import org.forester.sequence.Sequence;
10 import org.forester.util.ForesterUtil;
12 public class SequenceWriter {
14 public static enum SEQ_FORMAT {
18 public static StringBuilder toFasta( final Sequence 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 Sequence seq, final Writer w, final int width ) throws IOException {
49 w.write( seq.getIdentifier().toString() );
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<Sequence> seqs, final File file, final SEQ_FORMAT format, final int width )
72 final Writer w = ForesterUtil.createBufferedWriter( file );
73 SequenceWriter.writeSeqs( seqs, w, format, width );
77 public static void writeSeqs( final List<Sequence> seqs,
79 final SEQ_FORMAT format,
80 final int width ) throws IOException {
83 for( final Sequence s : seqs ) {
84 toFasta( s, writer, width );
85 writer.write( ForesterUtil.LINE_SEPARATOR );
89 throw new RuntimeException( "unknown format " + format );