Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileOutputStream set encoding to utf-8

Tags:

java

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();
like image 736
istshrna istshrna Avatar asked Dec 14 '15 14:12

istshrna istshrna


2 Answers

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();
like image 112
Remy Lebeau Avatar answered Oct 06 '22 10:10

Remy Lebeau


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));
like image 27
assylias Avatar answered Oct 06 '22 11:10

assylias