Change encoding of an existing file in Java?

I need to programmatically change the encoding of the * nix script set to UTF-8 from Java. I won’t write anything to them, so I’m trying to find the easiest way to do this. Files are not too many and not so big. I could:

  • Write an empty string using OutputStream with UTF-8 set as encoding
  • Since I already use FileUtils (from Apache Commons), I could read | write the contents of these files, passing UTF-8 as an encoding

It doesn’t matter, but has anyone encountered this case before? Are there any flaws in both approaches?

+7
source share
1 answer

As requested, and since you are using io shared resources, here is an example code (error checking in the wind):

import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class Main { public static void main(String[] args) throws IOException { String filename = args[0]; File file = new File(filename); String content = FileUtils.readFileToString(file, "ISO8859_1"); FileUtils.write(file, content, "UTF-8"); } } 
+11
source

All Articles