-3

I try to write a program which will take as an input some text and then the name of the target encoding (ASCII, UTF-8, etc.).

Is there any way in Java to write something like this?

String encodedText = String.encode(text, encoding);

Thanks for any suggestions!

3 Answers3

0

You can use the following code to convert from byte[] to String with your intended character set.

new String(bytes, StandardCharsets.UTF_8);

or as Andy Turner mentioned in the comments, you can use the getBytes method of the String class.

text.getBytes(StandardCharsets.UTF_8)
Hossein Mobasher
  • 4,382
  • 5
  • 46
  • 73
0
String decodeText(String input, String encoding) throws IOException {
    return 
      new BufferedReader(
        new InputStreamReader(
          new ByteArrayInputStream(input.getBytes()), 
          Charset.forName(encoding)))
        .readLine();
}

Should do the trick.

Here is a well written post about how encoding works. I suggest you read through it before implementing this solution. Java-Char-Encoding

0

If you want to do it for whole files you can make a loop which reads a line from a FileReader and writes it through a FileWriter. Both classes accept charsets to their constructors since java 11.

RAVN Mateus
  • 560
  • 3
  • 13