2

I'm using something like this in a java application to write to a file:

BufferedWriter out = new BufferedWriter(new FileWriter(out1, true)); //where out1 is a File.

When I run it from netBeans the output is good. When I try to run it from the windows command line (the intended use; using the jar) the accented characters go crazy. I think that is have something to do with the chars encoding.

e.g. (the output file is a HTML one);

I want to write this:

"<p>Inclinação(1):</p>"

Using Win command line, appears this:

<p>Inclina褯(1):</p>
kukido
  • 10,431
  • 1
  • 45
  • 52
nervousDev
  • 72
  • 9

3 Answers3

1

Use OutputStreamWriter with FileOutputStream so you can explicitly specify the Charset.

    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out1, true), "UTF-8"));
Dmitri
  • 8,999
  • 5
  • 36
  • 43
  • I will give it a try. btw, what is the better charset to use with accented chars and compatible with HTML 4.01 Transitional ? – nervousDev Jan 10 '14 at 22:27
  • Pretty much always stick with `utf-8`, unless you have a specific reason not to. I do believe that the default in 4 is `iso-8859-1` (HTML5 is `utf-8`), so you should add a `meta` charset declaration. – Dmitri Jan 10 '14 at 22:43
  • Using your option, I'm not able to write to the next line without using .newLine() ; My entire app is using "\n" with strings that I write. – nervousDev Jan 10 '14 at 22:46
  • Not sure what you mean... you're using `write`, so: `out.write("foo\n");`. `println()`, `newLine()`, etc. are system-dependent (hence the difference between NetBeans and Windows shell), so that's probably not what you want to begin with. – Dmitri Jan 10 '14 at 22:50
  • So, what is the best way to do print with that specs ? – nervousDev Jan 10 '14 at 22:54
  • Just that: `out.write("foo\n");` – Dmitri Jan 10 '14 at 23:04
  • I'm using this right now: BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("oi.txt", true), "ISO-8859-15")); out.write("oi\n"); out.write("yes"); out.close(); – nervousDev Jan 10 '14 at 23:06
  • And the output is(after I runned the teste a few times): "oi yesoi yesoi yesoi yesoi yesoi yesoi yes" – nervousDev Jan 10 '14 at 23:07
  • how are you viewing the output? – Dmitri Jan 10 '14 at 23:11
  • I was viewing the wrong file, sorry mate. It has been a long day ,eheh. Thanks, a lot. Cheers – nervousDev Jan 10 '14 at 23:17
1

I believe that you need to specify an encoding, unfortunately FileWriter does not provide any ways to set it, though there are other options such as:

BufferedWriter out = new BufferedWriter
    (new OutputStreamWriter(new FileOutputStream(out1, true),"UTF-8")); 
Алексей
  • 1,847
  • 12
  • 15
0

I resolve this problem using the parameter 8859_1, you can learn more about here http://www.cafeconleche.org/books/xmljava/chapters/ch03s03.html.

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(baos, "8859_1"));