Java BufferedWriter object with utf-8
No. FileWriter
doesn't let you specify the encoding, which is extremely annoying. It always uses the system default encoding. Just suck it up and use OutputStreamWriter
wrapping a FileOutputStream
. You can still wrap the OutputStreamWriter in a BufferedWriter of course:
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8));
Or as of Java 8:
BufferedWriter out = Files.newBufferedWriter(Paths.of(path));
(Of course you could change your system default encoding to UTF-8, but that seems a bit of an extreme measure.)
You can use improved FileWriter, improved by me.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
/**
* Created with IntelliJ IDEA.
* User: Eugene Chipachenko
* Date: 20.09.13
* Time: 10:21
*/
public class BufferedFileWriter extends OutputStreamWriter
{
public BufferedFileWriter( String fileName ) throws IOException
{
super( new FileOutputStream( fileName ), Charset.forName( "UTF-8" ) );
}
public BufferedFileWriter( String fileName, boolean append ) throws IOException
{
super( new FileOutputStream( fileName, append ), Charset.forName( "UTF-8" ) );
}
public BufferedFileWriter( String fileName, String charsetName, boolean append ) throws IOException
{
super( new FileOutputStream( fileName, append ), Charset.forName( charsetName ) );
}
public BufferedFileWriter( File file ) throws IOException
{
super( new FileOutputStream( file ), Charset.forName( "UTF-8" ) );
}
public BufferedFileWriter( File file, boolean append ) throws IOException
{
super( new FileOutputStream( file, append ), Charset.forName( "UTF-8" ) );
}
public BufferedFileWriter( File file, String charsetName, boolean append ) throws IOException
{
super( new FileOutputStream( file, append ), Charset.forName( charsetName ) );
}
}
As the documentation for FileWriter explains,
The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
There's no reason you can't construct your BufferedWriter on top of the OutputStreamWriter though.
Use the method, Files.newBufferedWriter(Path path, Charset cs, OpenOption... options)
As requested by Toby, here is the sample code.
String errorFileName = (String) exchange.getIn().getHeader(HeaderKey.ERROR_FILE_NAME.getKey());
String errorPathAndFile = dir + "/" + errorFileName;
writer = Files.newBufferedWriter(Paths.get(errorPathAndFile), StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
try {
writer.write(MESSAGE_HEADER + "\n");
} finally {
writer.close();
}