简体   繁体   中英

FileOutputStream set encoding to utf-8

a want to set a file to utf-8

the FileOutputStream takes just two parameter

my code is

 PrintWriter kitaba1 = null;

    try {
       kitaba1 = new PrintWriter(new FileOutputStream(new File(ismmilaf), true ));

    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }

    //kitaba1.println(moarif1);
    kitaba1.close();

You need to use OutputStreamWriter so you can specify an output charset. You can then wrap that in a PrintWriter or BufferedWriter if you need printing semantics:

PrintWriter kitaba1 = null;

try {
   kitaba1 = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(ismmilaf), true), StandardCharsets.UTF_8));

} catch (FileNotFoundException ex) {
    ex.printStackTrace();
}

//kitaba1.println(moarif1);
kitaba1.close();

BufferedWriter kitaba1 = null;

try {
   kitaba1 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(ismmilaf), true), StandardCharsets.UTF_8));

} catch (FileNotFoundException ex) {
    ex.printStackTrace();
}

//kitaba1.write(moarif1);
//kitaba1.newLine()
kitaba1.close();

FileOutputStream is meant to be used to write binary data. If you want to write text you can use a FileWriter or an OutputStreamWriter.

Alternatively you could use one of the methods in the Files class , for example:

Path p = Paths.get(ismmilaf);
Files.write(p, moarif1.getBytes(StandardCharsets.UTF_8));

You can specify it as the third param of PrintStream like this:

foostream = new FileOutputStream(file, true);
stream  = new PrintStream(foostream, true, "UTF_8");
stream.println("whatever");

or using StandardCharsets.DesiredEncoding (i didn't remember it well but maybe you need to use .toString() on it, like:

stream  = new PrintStream(foostream, true, StandardCharsets.UTF-8.toString());

That is because you are using different charset and those characters do not belong to that, could you try using UTF-8 , eg:

FileOutputStream fos = new FileOutputStream("G://data//123.txt");
        Writer w = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8));
        String stringa = "L’uomo più forte";
        w.write(stringa);
        w.write("\n");
        w.write("pause");
        w.write("\n");
        w.flush();
        w.close();

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