Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write Java String to file with special encoding

I have got the Java String ôð¤ Ø$î1<¨ V¸dPžÐ ÀH@ˆàÀༀ@~€4` which I would like to write to a file with ANSI encoding.

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output),"windows-1252"));
    try {   
        out.append(str);
    } finally {
        out.close();
    }

Debugger says that str contains ôð¤ Ø$î1<¨ V¸dPÐ ÀH@àÀà¼@~4. As soon as I write it to the output file, the file only contains ?ÒÜ@4. So whats wrong with my method writing to the File?

Sorry for this weird strings - I am trying to rewrite a delphi 7 function in java. These strings are the only samples I have got.

like image 947
gorootde Avatar asked Dec 27 '25 16:12

gorootde


1 Answers

If I run

String text = "ôð¤ Ø$î1<¨ V¸dPžÐ ÀH@ˆàÀༀ@`~€4";
Writer writer = new OutputStreamWriter(new FileOutputStream("test.txt"), "windows-1252");
writer.append(text);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt"), "windows-1252"));
String line = br.readLine();
br.close();
System.out.println(line.length() + ": '" + line + "' matches " + line.equals(text));

it prints

32: 'ôð¤ Ø$î1<¨ V¸dPžÐ ÀH@ˆàÀༀ@`~€4' matches true

so no characters are lost in translation.


If I change the encoding to "US-ASCII" I get the following output

32: '??? ?$?1<? V?dP?? ?H@??????@`~?4' matches false
like image 116
Peter Lawrey Avatar answered Dec 31 '25 17:12

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!