views:

5306

answers:

5

Hi there,

I have some current code and the problem is its creating a 1252 codepage file, i want to force it to create a UTF-8 file

Can anyone help me with this code, as i say it currently works... but i need to force the save on utf.. can i pass a parameter or something??

this is what i have, any help really appreciated

var out = new java.io.FileWriter( new java.io.File( path )),
        text = new java.lang.String( src || "" );
 out.write( text, 0, text.length() );
 out.flush();
 out.close();
+10  A: 

Instead of using FileWriter, create a FileOutputStream. You can then wrap this in an OutputStreamWriter, which allows you to pass an encoding in the constructor. Then you can write your data to that.

skaffman
... and curse at Sun not putting in a constructor to FileWriter which takes a Charset.
Jon Skeet
It does seem like an odd oversight. And they still haven't fixed it.
skaffman
@Jon Skeet: Given that FileWriter is a wrapper for FileOutputStream that assumes the default encoding and buffer size, wouldn't that defeat the point?
R. Bemrose
Sorry, I meant for OutputStreamWriter, not for FileOutputStream.
R. Bemrose
thankyou .. it is now fixed.. writing a utf-8 file.. thanks again
mark smith
+5  A: 

Try this

try {
        Writer out = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream("outfilename"), "UTF8"));
        out.write(aString);
        out.close();
    } catch (UnsupportedEncodingException e) {
    } catch (IOException e) {
    }
Markus Lausberg
I think there is a typo. `Writer out = ...` should be corrected to`BufferedWriter out = ... ` .
asmaier
Writer is the Abstract Class, BufferedWriter is implementing and write() + close() are declarated.
Markus Lausberg
+2  A: 
var out = new java.io.PrintWriter(new java.io.File(path), "UTF-8");
text = new java.lang.String( src || "" );
out.print(text);
out.flush();
out.close();
boxofrats
A: 

Try using FileUtils.write from Apache Commons.

You should be able to do something like:

File f = new File("output.txt");
FileUtils.write(f, "Contents", "UTF-8");

This will create the file if it does not exist.

A_M
A: 

All of the answers given here wont work since java's UTF-8 writing is bugged.

http://tripoverit.blogspot.com/2007/04/javas-utf-8-and-unicode-writing-is.html

Emperorlou