This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Print header of bam file using htsjdk library

Hi, I am using htsjdk library and want to print the header of bam file. I tried but the following code just prints the first header line again and again. I want all header lines. Any suggestions?? Thanks for your time and consideration.

File bamFile =new File("SampleFile.bam");

SamReader sr = 
SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT).open(bamFile);     

SAMRecordIterator r = sr.iterator();

while(r.hasNext()) {

    SAMRecord rec=r.next();    

    System.out.println(rec.getHeader());

}

r.close();

sr.close();
ngs samformat

2 answers

I think you should replace rec.getHeader() with:

rec.getHeader().getTextHeader()

https://github.com/samtools/htsjdk/blob/master/src/main/java/htsjdk/samtools/SAMTextHeaderCodec.java

 StringWriter str = new StringWriter();
 new SAMTextHeaderCodec().encode(str, sr.getFileHeader());
System.out.println(str);

Log in to answer this question.