简体   繁体   中英

Java Latin1 encoded text file

I am trying to create an ISO-8859-15 encoded text file from a java method:

public void createLatin1EncodedTextFile(File latin1File, Integer numberOfLines) throws UnsupportedEncodingException,
  FileNotFoundException {

  BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(latin1File), "8859_1"));
  try {
    for (int i = 0; i < numberOfLines; i++) {
      bw.write(new String(generateRandomString().getBytes(), "ISO-8859-15"));
    }
  }
  catch (IOException e) {
    e.printStackTrace();
  }
  finally {
    try {
      if (!bw.equals(null)) {
        bw.close();
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

The method generateRandomString() generates a random sequence of characters. The method works fine but when I open it with notepad++ it says that the file is encoded in UTF-8.

You're doing far more work than you need to do. The encoding of the file is whatever encoding you pass to the OutputStreamWriter:

try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(latin1File), "ISO-8859-15"))) {
    for (int i = 0; i < numberOfLines; i++) {
        bw.write(generateRandomString());
    }
}

The whole point of a Writer is that it accepts characters (or Strings) and takes care of the task of encoding them.

The fact that your parameter is named latin1File has me wondering whether you really want to create an ISO-8859-15 file, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM