簡體   English   中英

使用utf-8的Java BufferedWriter對象

[英]Java BufferedWriter object with utf-8

我有以下代碼,我想使輸出流使用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不允許您指定編碼,這非常煩人。 它始終使用系統默認編碼。 只需將其吸收並使用OutputStreamWriter包裝FileOutputStream 您當然可以將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();
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM