private static boolean isGoodCharset(@NotNull VirtualFile virtualFile, @NotNull Charset charset) {
    FileDocumentManager documentManager = FileDocumentManager.getInstance();
    Document document = documentManager.getDocument(virtualFile);
    if (document == null) return true;
    byte[] loadedBytes;
    byte[] bytesToSave;
    try {
      loadedBytes = virtualFile.contentsToByteArray();
      bytesToSave = new String(loadedBytes, charset).getBytes(charset);
    }
    catch (Exception e) {
      return true;
    }
    if (loadedBytes.length == 0 && bytesToSave.length == 0) {
      // hold on, file was just created, no content was written yet
      return true;
    }
    byte[] bom = virtualFile.getBOM();
    if (bom != null && !ArrayUtil.startsWith(bytesToSave, bom)) {
      bytesToSave = ArrayUtil.mergeArrays(bom, bytesToSave); // for 2-byte encodings String.getBytes(Charset) adds BOM automatically
    }

    return Arrays.equals(bytesToSave, loadedBytes);
  }
private static boolean isGoodCharset(@NotNull VirtualFile virtualFile, @NotNull Charset charset)