Animalz
Animalz

Reputation: 88

Representing Japanese letters in a Java created HTML-file

I want to write Japanese letters into a Java created HTML-file. For doing so, I created a FileOutputStream creating a .html document at a destination (like Desktop, documents). I wrote some HTML-Code into my Java Code, so it will translate it properly:

package main;

import java.io.DataOutputStream;

public class Streamer {
  static String address;
  static String output;

  public Streamer() {}

  static String html_begin = "<!DOCTYPE html><html><body>";
  static String header = "<head><meta lang=\"japanese\" charset=\"unicode\"></head>";
  static String html_end = "</html></body>";

  public static void output(String s, String s2) {
    address = s2;
    output = s;
    setAddress(s2);


    try
    {
      DataOutputStream stream = new DataOutputStream(new java.io.FileOutputStream(address));
      stream.writeBytes(html_begin);
      stream.writeBytes(header);
      stream.writeBytes(output);
      stream.writeBytes(html_end);


      stream.close();
    }
    catch (java.io.IOException localIOException) {}
  }

.....}

Even with declaring the charset as Unicode and the language as Japanese, the created file is showing me some random signs...

For information: The code directly transforms a given code at a JTextArea (String) into the HTML-embedded document. The given address as argument of FileOutputStream is just the destination the created file shall appear.

The method setAdress is just the setting method of these address.

Upvotes: 1

Views: 611

Answers (1)

Andreas
Andreas

Reputation: 159086

Do not use DataOutputStream to write text files. Use a Writer to write text files. Better yet, use a PrintWriter.

To write text files with Japanese characters, you need the file to be encoded in a character set that supports Japanese characters, e.g. UTF-8 or UTF-16.

Also, you should use try-with-resources.

try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(Paths.get(address), StandardCharsets.UTF_16))) {
    out.println(html_begin);
    out.println(header);
    out.println(output);
    out.println(html_end);
} catch (IOException e) {
    e.printStackTrace();
}

Pre-Java 7 you would write:

try (PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(address), "UTF-16")))) {
    out.println(html_begin);
    out.println(header);
    out.println(output);
    out.println(html_end);
} catch (IOException e) {
    e.printStackTrace();
}

Upvotes: 3

Related Questions