SAMFileWriterFactory writerFactory = new SAMFileWriterFactory();
writerFactory.setUseAsyncIo(false);
// Farm each chromosome out to its own thread.
for (SAMSequenceRecord chr : rdr.getFileHeader().getSequenceDictionary().getSequences()) {
SAMFileWriter writer = writerFactory.makeSAMOrBAMWriter(
rdr.getFileHeader(), false, new File(outputDirectory + "/" + chr.getSequenceName() + ".bam"));
outputWriterMap.put(chr.getSequenceName(), writer);
BamSplitterThread thread = new BamSplitterThread(threads, filename, chr.getSequenceName(), writer);
threads.spawnThread(thread);
}
threads.waitForAllThreadsToComplete();
// Now go back and retrieve the unmapped reads.
System.err.println("Processing unmapped reads");
Iterator<SAMRecord> iter = rdr.queryUnmapped();
while (iter.hasNext()) {
SAMRecord read = iter.next();
// If this read is not assigned a position, but the mate is, include in the output BAM associated with mate's chromosome.
if (read.getReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX && read.getMateReferenceIndex() != SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX) {
SAMFileWriter writer = outputWriterMap.get(read.getMateReferenceName());
writer.addAlignment(read);
}
}
for (SAMFileWriter writer : outputWriterMap.values()) {
writer.close();
}
rdr.close();
long e = System.currentTimeMillis();