Here you can find the source of writeFileWithBom(File file, String content, String encoding)
public static void writeFileWithBom(File file, String content, String encoding) throws IOException
/**/*from www . j a v a 2 s.com*/ * Copyright 2009 Welocalize, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; public class Main{ static private final Logger logger = Logger.getLogger(FileUtil.class); static public final String UTF8 = "UTF-8"; static public final String UTF16LE = "UTF-16LE"; static public final String UTF16BE = "UTF-16BE"; public static void writeFileWithBom(File file, String content, String encoding) throws IOException { if (!file.exists()) { file.getParentFile().mkdirs(); } FileOutputStream out = null; try { out = new FileOutputStream(file); writeBom(out, encoding); out.write(content.getBytes(encoding)); } finally { if (out != null) { out.flush(); out.close(); } } } /** * Writes the BOM(Byte Order Mark) to the file. * * @param p_outputStream * @param encoding */ public static void writeBom(OutputStream outputStream, String encoding) { if (outputStream != null && encoding != null) { byte[] b = null; if (UTF8.equals(encoding)) { b = new byte[3]; b[0] = (byte) 0xef; b[1] = (byte) 0xbb; b[2] = (byte) 0xbf; } else if (UTF16LE.equals(encoding)) { b = new byte[2]; b[0] = (byte) 0xff; b[1] = (byte) 0xfe; } else if (UTF16BE.equals(encoding)) { b = new byte[2]; b[0] = (byte) 0xfe; b[1] = (byte) 0xff; } if (b != null) { try { outputStream.write(b); } catch (IOException e) { logger.error(e.getMessage(), e); } } } } }