-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!

2
  • 1
    byte[] theBytes = text.getBytes(encoding);. Strings are sequences of chars; the encoding is the mapping of that to a sequence of bytes. Commented Sep 29, 2021 at 12:31
  • baeldung.com/java-string-encode-utf-8 Commented Sep 29, 2021 at 12:32

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.