This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Java Samtools Api: Write Bam To Stdout

Hello,

I'm trying to use the Java API for picard/samtools to write a BAM file to standard output.

With the code below I can write SAM to stdout. However, I would like to write directly as BAM to stdout. Is it possible?

SAMFileWriterFactory sf= new SAMFileWriterFactory();
SAMFileWriter sw= sf.makeSAMWriter(mySamFileHeader, false, System.out);
sw.addAlignment(mySamRecord);

Many thanks

Dario

java picard samtools

1 answer

try to use:

makeBAMWriter(mySamFileHeader,false,new File("/dev/stdout"));

or try to create a BAMFileWriter with file=null (not tested, but it should work (?))

   return new  BAMFileWriter(System.out, (File)null)

Thanks Pierre! Your first option would work but I'm a bit reluctant to hard-coding "/dev/stdout". Your second option however put me in the right direction. This seems to work:

SAMFileHeader samFileHeader= sam.getFileHeader();                
SAMFileWriterFactory sf= new SAMFileWriterFactory();
BAMFileWriter sw= new BAMFileWriter((OutputStream)System.out, (File)null);
sw.setHeader(samFileHeader);
sw.addAlignment(rec);

Log in to answer this question.