Encoding em um arquivo TXT

1 resposta
R

Pessoal, estou com uma função que cria um arquivo TXT escrevendo os dados nele.
O problema é que os acentos, Ç, etc… saem tudo como o caracter ‘?’…

O código segue abaixo…

File f = new File( pathResolver.getPathTemporario() + File.separator + nomeArq);
					PrintWriter pw = new PrintWriter(f);

.....

pw.println( String.format("%s/%s|TIM %s|AGENCIA|%s|%s|%d|%s|%d|%s|%s|%s|%s|%s|ICCID|%s|%s", mesAbrev, anoAbrev
								, (String) aux[0], (String) aux[0], (String) aux[2], (Integer) aux[1], (String) aux[4], (Integer) aux[3], custCode, (String) aux[6],
								(String) aux[7], EthiUtil.sdfDataHMS.format( (Date) aux[10]), (Short) aux[8] + (String) aux[9], tipo, plano  ) );

Estou utilizando um PrintWriter para gravar este arquivo…
Como faço para esta String, sair com os acentos, Ç, etc ?

Att
Rodrigo Kerkhoff

1 Resposta

B

Isso é chato…

Para isso, vc terá que prestar atenção em 3 coisas:
0. Se os dados utilizados para compor o conteúdo do arquivo estão corretos (acentuados corretamente)

  1. o formato q vc está gravando o arquivo
  2. o formato que vc está lendo o arquivo

Para os itens 1 e 2, basta vc padronizar o Character Set

O java suporta os seguintes characterSets (Extraído da javadoc):
US-ASCII Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
ISO-8859-1 ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
UTF-8 Eight-bit UCS Transformation Format
UTF-16BE Sixteen-bit UCS Transformation Format, big-endian byte order
UTF-16LE Sixteen-bit UCS Transformation Format, little-endian byte order
UTF-16 Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark

Então, para gravar, use o PrintWriter com o charset especificado:

new PrintWriter(File file, "UTF-8");

E use o mesmo charset para ler o arquivo depois (Se naõ me engano, é algo assim…):

DataInputStream dis = new DataInputStream(new FileInputStream(file)); byte[] conteudoArquivo = new byte[file.length()]; dis.readfully(conteudoArquivo); String conteudo = new String(conteudoArquivo, "UTF-8")

PS: o format não precisa de cast… então, tenta diminuir a poluição de código e a suas chances de ganhar uma tendinite :wink:

Criado 29 de setembro de 2009
Ultima resposta 9 de out. de 2009
Respostas 1
Participantes 2