Home > Java > JavaBase > body text

How to solve garbled characters when writing files in Java

Release: 2019-12-30 13:57:14
Original
3043 people have browsed it

How to solve garbled characters when writing files in Java

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();
        }
    }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!