public static @NotNull Pair.NonNull<Charset, byte[]> charsetForWriting(@Nullable Project project,
                                                                         @NotNull VirtualFile virtualFile,
                                                                         @NotNull String text,
                                                                         @NotNull Charset existing) {
    Charset specified = extractCharsetFromFileContent(project, virtualFile, text);
    Pair.NonNull<Charset, byte[]> chosen = chooseMostlyHarmlessCharset(existing, specified, text);
    Charset charset = chosen.first;

    // in the case of "UTF-16", OutputStreamWriter sometimes adds BOM on its own (see JDK-6800103)
    byte[] bom = virtualFile.getBOM();
    Charset fromBom = bom == null ? null : CharsetToolkit.guessFromBOM(bom);
    if (fromBom != null && !fromBom.equals(charset)) {
      chosen = Pair.createNonNull(fromBom, text.getBytes(fromBom));
    }
    return chosen;
  }
public static @NotNull Pair.NonNull<Charset, byte[]> charsetForWriting(@Nullable Project project,
                                                                         @NotNull VirtualFile virtualFile,
                                                                         @NotNull String text,
                                                                         @NotNull Charset existing)