简体   繁体   中英

How to save text file with UTF-8 encoding in java?

I am facing a problem in saving a text file in UTF-8 format using java. When i click on save as for the generated text file, it gives ANSI as text format but not as UTF-8. Below is the code i am writing while creating the file:

    String excelFile="";

    excelFile = getFullFilePath(fileName);
    File file = new File(excelFile + fileName,"UTF-8");
    File output = new File(excelFile,"UTF-8");

    FileUtils.writeStringToFile(file, content, "UTF-8");

While creating the text file, I am using UTF-8 encoding, but the file still shows the encoding as ANSI while saving. Kindly help.

Instead of using File, create a FileOutputStream. Try this.

Writer out = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream("outfilename"), "UTF-8"));
try {
    out.write(aString);
} finally {
    out.close();
}

I had a problem very similar to that and I solved saving the original file with the UTF-8 encoding. In this case, go to the excel file and save it again, or create a new file and copy the content, and make sure that its encoding is UTF-8. This link has a tutorial on how to save an excel file with UTF-8 encoding: https://help.surveygizmo.com/help/encode-an-excel-file-to-utf-8-or-utf-16 . At the most your code seems to be correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM