1

The following code appends data to the given file in java application. But when put this code in servlet, the file becomes empty. Why this?

try {            
  OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("C:\\root.properties", true), "UTF-8");
  BufferedWriter fbw = new BufferedWriter(writer);
  String s = "root.label.1130.2=قسيمات";      
  fbw.write(new String(s.getBytes("iso-8859-1"), "UTF-8"));
  fbw.newLine();
  fbw.close();
} catch (Exception e) {
  System.out.println("Error: " + e.getMessage());
} 
skmaran.nr.iras
  • 8,152
  • 28
  • 81
  • 116

2 Answers2

2

The string does contain non-ISO-8859-1 characters after the equals sign. You may want to check that the Java compilation accepts UTF-8 input, i.e. javac -encoding UTF-8. Also, replace "iso-8859-1" with "UTF-8" in getBytes().

See http://illegalargumentexception.blogspot.com/2009/05/java-rough-guide-to-character-encoding.html#javaencoding_sourcefiles for a nice write-up and other ways to encode the constant string.

mgaert
  • 2,338
  • 21
  • 27
  • @magaert:I get the correct output when I create a new file. But while appending there are problems in writing and in encoding. – skmaran.nr.iras Jan 10 '12 at 11:25
  • Oh, that focuses the question a bit. Also, you are aware that Java properties are usually ISO-8859-1 (with character quoting)? Are you sure you can read the UTF-8 properties file? See http://stackoverflow.com/a/3040771/1037626 – mgaert Jan 10 '12 at 11:32
1

Are you sure you are seeing any exception which might be thrown? Perhaps your servlet doesn't have permission to write to the file. I would try to debug your program to see what happens when this code is run.


What you are doing will corrupt many of the characters, but you should still get a file.

When I run this code I get a file with

root.label.1130.2=??????

which is what you would expect to get.

If I run this code

PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("root.properties", true), "UTF-8"));
String s = "root.label.1130.2=قسيمات";
pw.println(s);
pw.close();

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("root.properties"), "UTF-8"));
String line;
while ((line = br.readLine()) != null) {
    for (int i = 0; i < line.length(); i++) {
        char ch = line.charAt(i);
        if (ch >= ' ' && ch < 127)
            System.out.print(ch);
        else
            System.out.printf("\\u%04x", (int) ch);
    }
    System.out.println();
}

prints the following, showing that the Arabic characters have not been mangled.

root.label.1130.2=\u0642\u0633\u064a\u0645\u0627\u062a

the file now contains

root.label.1130.2=قسيمات

as expected.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130