简体   繁体   中英

saving to utf-8 file

I'm trying to save a .txt file in the UTF_8 format, but I don't understand where I should add that to my code. Here's what I got.

String fileStringName =  userHome + "/wordsearch directory/Puzzle.txt";
        File filePath = new File(userHome + "/wordsearch directory/Puzzle.txt");
        File dirPath = new File (userHome + "/wordsearch directory");           
        //new method just made
        //make pop up jpane displaying puzzle ID.
        boolean filePathExists = false;
        if(!filePath.exists())
        {
            filePathExists = dirPath.mkdirs();
            try {
                //BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),"UTF-8"));
                writer = new PrintWriter(new BufferedWriter(new FileWriter(fileStringName,  true)));
        //  Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileStringName), "UTF-8"));
            } catch (IOException e2) {
                writer = null;
                e2.printStackTrace();
            }
            writer.printf(savePuzzle.toString());
            writer.printf("\n");
            writer.close();

Try this:

File dirPath = new File (userHome + "/wordsearch directory");           
File filePath = new File(dirPath, "Puzzle.txt");

try {
    if (!dirPath.exists()) {
        dirPath.mkdirs();
    }
    Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8));
    writer.write(savePuzzle.toString());
    writer.write("\n"); // or writer.newLine()
    writer.close();
} catch (IOException e) {
    e.printStackTrace();
}

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