Java writes files to avoid garbled code as follows: (Recommended: java video tutorial)
/** * * @Title: writeFile * @Description: 写文件 * @param @param filePath 文件路径 * @param @param fileContent 文件内容 * @return void 返回类型 * @throws */ public static void writeFile(String filePath, String fileContent) { try { File f = new File(filePath); if (!f.exists()) { f.createNewFile(); } OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8"); BufferedWriter writer = new BufferedWriter(write); writer.write(fileContent); writer.close(); } catch (Exception e) { System.out.println("写文件内容操作出错"); e.printStackTrace(); } }
Main implementation code: OutputStreamWriter write = new OutputStreamWriter( new FileOutputStream(f), "UTF-8");
OutputStreamWriter is a bridge from a character stream to a byte stream: encoding the characters written into it into bytes using the specified character set. The character set it uses can be specified by name, explicitly specified, or the platform's default character set can be accepted.
Every call to the write() method causes the encoding converter to be called on the given character. The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer can be specified, but by default it is large enough for most purposes. Note that characters passed to the write() method are not buffered.
The constructor in the OutputStreamWriter stream can specify the character set, or take the default value without setting it.
For more java knowledge, please pay attention to the java basic tutorial column.
The above is the detailed content of How to solve garbled characters when writing files in Java. For more information, please follow other related articles on the PHP Chinese website!