A.R.K.S
A.R.K.S

Reputation: 1802

Alternatives to setting encoding in FileWriter - Java

I read that java documentation for FileWriter - it doesn't allow us to specify encoding. I'm using FileWriter in order to avoid the newline character that gets automatically appended while writing list of strings to a file(And I think this is the only thing I can use to achieve that).

I'm now facing a problem that some japanese characters in few properties file are written as "???", so I need to pass in the encoding information somehow. Is there any other way to either avoid the newline appending or a way to pass encooding info to FileWriter?

Upvotes: 1

Views: 2401

Answers (2)

Chase T
Chase T

Reputation: 116

If you're working with Path (Java 7+), you can use Files.newBufferedWriter(path, charset, options) to specify a Charset. (This also wraps your output in a BufferedWriter, which is nice.)

The classic alternative is to use OutputStreamWriter and pass a Charset that way.

Always passing a charset to writers is a good habit, even if you don't think it's likely to ever deal with non-ASCII content.

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198143

Don't use FileWriter, but instead new OutputStreamWriter(new FileOutputStream(file), encoding).

Upvotes: 4

Related Questions