private boolean detectCharset(byte[] buf) throws IOException {
    ByteCharsetDetector detector = new ByteCharsetDetector(new CharsetValidation(), userEncoding);
    ByteOrderMark bom = detector.detectBOM(buf);
    if (bom != null) {
      detectedCharset = Charset.forName(bom.getCharsetName());
      stream.skip(bom.length());
      return true;
    }

    detectedCharset = detector.detect(buf);
    return detectedCharset != null;
  }
@Test
  public void should_detect_charset_from_BOM() {
    Path basedir = Paths.get("src/test/resources/org/sonar/scanner/scan/filesystem/");

    assertThat(detectCharset(basedir.resolve("without_BOM.txt"), US_ASCII)).isEqualTo(US_ASCII);
    assertThat(detectCharset(basedir.resolve("UTF-8.txt"), US_ASCII)).isEqualTo(UTF_8);
    assertThat(detectCharset(basedir.resolve("UTF-16BE.txt"), US_ASCII)).isEqualTo(UTF_16BE);
    assertThat(detectCharset(basedir.resolve("UTF-16LE.txt"), US_ASCII)).isEqualTo(UTF_16LE);
    assertThat(detectCharset(basedir.resolve("UTF-32BE.txt"), US_ASCII)).isEqualTo(MetadataGenerator.UTF_32BE);
    assertThat(detectCharset(basedir.resolve("UTF-32LE.txt"), US_ASCII)).isEqualTo(MetadataGenerator.UTF_32LE);
  }