In: Computer Science
Convert UTF-8 to UTF-16 and Back
Write two Java programs and verify that they work.
Program 1 should:
Program 2 should do the same as program 1, except program 2 goes from UTF-16 to UTF-8
Submit:
import java.io.*;
public class WriteUTF8 {
public static void main(String[] args) {
File file = new
File("utf8_output.txt");
FileOutputStream fs= null;
try {
fs = new
FileOutputStream(file);
}
catch (FileNotFoundException fnfe)
{
System.err.println("file not found");
}
try {
fs.write("Фёдор".getBytes("UTF-8"));
fs.close();
}
catch(IOException ioe){
System.err.println("unable to write to file");
}
}
}
---
import java.io.*;
public class WriteUTF16 {
public static void main(String[] args) {
File file = new
File("utf16_output.txt");
FileOutputStream fs= null;
try {
fs = new
FileOutputStream(file);
}
catch (FileNotFoundException fnfe)
{
System.err.println("file not found");
}
try {
fs.write("Фёдор".getBytes("UTF-16"));
fs.close();
}
catch(IOException ioe){
System.err.println("unable to write to file");
}
}
}
--
WriteUTF16.java
import java.io.*;
public class WriteUTF16 {
public static void main(String[] args) {
File file = new File("utf16_output.txt");
FileOutputStream fs= null;
try {
fs = new FileOutputStream(file);
}
catch (FileNotFoundException fnfe) {
System.err.println("file not found");
}
try {
fs.write("Фёдор".getBytes("UTF-16"));
fs.close();
}
catch(IOException ioe){
System.err.println("unable to write to file");
}
}
}
WriteUTF8.java
import java.io.*;
public class WriteUTF8 {
public static void main(String[] args) {
File file = new File("utf8_output.txt");
FileOutputStream fs= null;
try {
fs = new FileOutputStream(file);
}
catch (FileNotFoundException fnfe) {
System.err.println("file not found");
}
try {
fs.write("Фёдор".getBytes("UTF-8"));
fs.close();
}
catch(IOException ioe){
System.err.println("unable to write to file");
}
}
}
UTF16 Output
UTF8 Output
Running Program