带有utf-8的Java BufferedWriter对象
我有以下代码,我想使输出流使用utf-8。 基本上我有像é
这样的字符,显示为é
所以它看起来像编码问题。
我见过很多使用的例子……
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(path),"UTF-8");
我目前的代码是……
BufferedWriter out = new BufferedWriter(new FileWriter(DatabaseProps.fileLocation + "Output.xml"));
是否可以将此对象定义为UTF-8而无需使用OutputStreamWriter?
谢谢,
不, FileWriter
不允许您指定编码,这非常烦人。 它始终使用系统默认编码。 只需将其吸收并使用包装FileOutputStream
OutputStreamWriter
。 您当然可以将OutputStreamWriter包装在BufferedWriter中:
BufferedWriter out = new BufferedWriter (new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8));
或者从Java 8开始:
BufferedWriter out = Files.newBufferedWriter(Paths.of(path));
(当然,您可以将系统默认编码更改为UTF-8,但这似乎有点极端。)
您可以使用改进的FileWriter,由我改进。
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 ) ); } }
正如FileWriter的文档所解释的那样,
此类的构造函数假定默认字符编码和默认字节缓冲区大小是可接受的。 要自己指定这些值,请在FileOutputStream上构造OutputStreamWriter。
没有理由你不能在OutputStreamWriter之上构造你的BufferedWriter。
使用方法Files.newBufferedWriter(Path path,Charset cs,OpenOption … options)
根据Toby的要求,这是示例代码。
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(); }