Slashking
Slashking

Reputation: 1

BufferedReader/Writer not working correctly with Special Chars

I ran into a little problem with Cipher and BufferedReader/Writer in Java. Everything works fine, if anyone wants my code nethertheless I can post it if you want. The problem is if I try to convert the encrypted bytes to a String (which works fine) then write it to a file with BufferedWriter with the following setup:

    FileWriter fwrit = new FileWriter(file);
BufferedWriter buffwrit = new BufferedWriter(fwrit); //The writer itself
String encTextString = new String(encText,"ISO-8859-1"); //The String that gets written later

This setup lets the Writer write special chars and I think the problem is not here (if it is please tell me). (Yes I already checked if decrypting without writing it to a file and loading again works and it does work.) The problem is I cant get the BufferedReader set up correctly, is there a way or a other writertype that reads the chars correctly?

Upvotes: 0

Views: 607

Answers (2)

Russell Zahniser
Russell Zahniser

Reputation: 16364

From the FileWriter javadoc:

"Convenience class for writing character files. 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."

The default charset is probably UTF-8. So, if you want to write ISO-8859-1, you would need to do:

new OutputStreamWriter(new FileOutputStream(file), Charset.forName("ISO-8859-1"))

More to the point, though, if your goal is to get the encoded bytes into the file without alteration, then...

"FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream."

Upvotes: 2

GerritCap
GerritCap

Reputation: 1616

It is probably better not to use FileWriter, that class is just a convenient class to wrap a FileOutputStream into a OutputStreamWriter.

OutputStreamWriter has constructors to encode your non ascii characters using a specific encoding.

FileWriter lacks those....

Upvotes: 0

Related Questions