code: public static void checkBamOrCramFile(InputStream is, String bamFileName, boolean checkSort) throws IOException {
          SamReaderFactory srf = SamReaderFactory.make();
          srf.validationStringency(ValidationStringency.LENIENT);
  
          SamReader reader = srf.open(SamInputResource.of(is));
          SAMFileHeader fileHeader = reader.getFileHeader();
          SAMFileHeader.SortOrder sortOrder = fileHeader.getSortOrder();
          reader.close();
  
          if (reader.type().equals(SamReader.Type.SAM_TYPE)) {
              throw new IOException("Expected binary SAM file. File " + bamFileName + " is not binary.");
          }
  
          if (checkSort) {
              switch (sortOrder) {
                  case coordinate:
                      break;
                  case queryname:
                  case unsorted:
                  default:
                      throw new IOException("Expected sorted file. File '" + bamFileName + "' is not sorted by coordinates("
                              + sortOrder.name() + ")");
              }
          }
      }
docs: Check if the file is a sorted binary bam file.
  
  @param is          Bam InputStream
  @param bamFileName Bam FileName
  @param checkSort
  @throws IOException