user1769735
user1769735

Reputation: 143

How to change text file coding charset using java

As in subject. How to rewrite the file with different charset?

Where are can find available encodings - final static ints?

    FileInputStream fis = new FileInputStream(inputFile);
    InputStreamReader isr = new InputStreamReader(fis, inputEncoding);
    BufferedReader in = new BufferedReader(isr);

    FileOutputStream fos = new FileOutputStream(outputFile);
    OutputStreamWriter osw = new OutputStreamWriter(fos, outputEncoding);
    BufferedWriter out = new BufferedWriter(osw);

    String line = in.readLine();
    out.write(line);

Upvotes: 0

Views: 216

Answers (2)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78629

The supported encoding formats are specified in the JDK Documentation.

As per the conversion, you can use

Upvotes: 0

BalusC
BalusC

Reputation: 1109322

As in subject. How to rewrite the file with different charset?

I'm not sure why you asked this question as your code seems legit, although it copies only 1 line (and swallows newlines). I wouldn't have used readLine(), but just read() in a loop, maybe with a buffer. This way you copy everything without modifying/swallowing newlines.


Where are can find available encodings - final static ints?

By Charset#availableCharsets().

SortedMap<String, Charset> availableCharsets = Charset.availableCharsets();
// ...

Upvotes: 1

Related Questions