In: Computer Science
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
Note: we are supposed to write two java programs, the first program should read utf8 encoded text file and the second program should write utf16 text file. So, if you can give me the java code that can read and write utf8 and utf16 text files respectively , I would be happy. Thank you.
//Program 1
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");
}
}
}
--
//Program 2
import java.nio.charset.Charset;
public class StringLength{
public static void printBytes(byte[] byteArr){
System.out.print("Bytes ( in hex ): ");
for ( byte b : byteArr ){
System.out.print(String.format("%02X ", b));
}
System.out.println("");
}
public static void inspectBytesOfText(String data, String textEncoding) {
System.out.println("\n\n**********************************");
System.out.println( "************** " + textEncoding + " ************\n");
System.out.println("Length of string " + data + " = " + String.valueOf(data.length()));
byte[] dataBytes = data.getBytes(Charset.forName(textEncoding));
System.out.println("Number of bytes in " + data + " = " + dataBytes.length);
printBytes(dataBytes);
}
public static void main(String[] args){
inspectBytesOfText("Фёдор", "UTF-8");
inspectBytesOfText("Фёдор", "UTF-16");
inspectBytesOfText("hello", "UTF-8");
inspectBytesOfText("hello", "UTF-16");
// Not that eclipse ( at least on my computer at 10:49 AM of 9/29/2020 )
// does not perfectly support unicode strings.
// When I type an emoji with a halo in, the following quotation mark is
//displayed in a weird way.
inspectBytesOfText("😇", "UTF-8");
inspectBytesOfText("😇", "UTF-16");
// if you know a foreign language, try running this method with a string from that language/
// try using emojis too.
}
}