0

I am trying to save a .txt file since a JAVA code, in a Windows 7 machine, and it encodes the code in ANSI, but when I do the same in a Windows Server 2000 the code is saved in UTF.

I am doing different testings and I checked that the encoding is changing when I run the code each time in Windows Server 2000 without changes on the code.

I´m saving the file in a zip file and the code is the next (I have changed "Cp1252" by "ISO-8859-1" but the result is the same):

public byte[] getBytesZipFile(String nombreFichero, String input) throws IOException {

    String tempdir = System.getProperty("java.io.tmpdir");
    if (!(tempdir.endsWith("/") || tempdir.endsWith("\\"))) {
        tempdir = tempdir + System.getProperty("file.separator");
    }

    File tempFile = new File(tempdir + nombreFichero + ".txt");
    try {
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "Cp1252"));

        bufferedWriter.write(input);
        bufferedWriter.flush();
        bufferedWriter.close();

        ByteArrayOutputStream byteArrayOutputStreambos = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStreambos);

        FileInputStream fileInputStream = new FileInputStream(tempFile);

        zipOutputStream.putNextEntry(new ZipEntry(tempFile.getName()));

        byte[] buf = new byte[1024];

        int len;
        while ((len = fileInputStream.read(buf)) > 0) {
            zipOutputStream.write(buf, 0, len);
        }

        zipOutputStream.closeEntry();
        fileInputStream.close();

        zipOutputStream.flush();
        zipOutputStream.close();

        return byteArrayOutputStreambos.toByteArray();
    } finally {
        tempFile.delete();
    }
}

Thanks by the help and answers and regards

sisyphus
  • 6,174
  • 1
  • 25
  • 35

1 Answers1

0

It is because of the default encoding of the JVM.

Check this question for how to change the default encoding: Setting the default Java character encoding?

And check this external articel for setting the encoding of your specific file: http://www.mkyong.com/java/how-to-write-utf-8-encoded-data-into-a-file-java/

Community
  • 1
  • 1
adranale
  • 2,835
  • 1
  • 21
  • 39