I have tested the best and more secure way to produce UTF-8 text file, but when I'm using it in multiple abstract classes, it produce ANSI format files not UTF-8 format! Is there any bug or something to preventing it? Again, my code is correct and when I put all code in a single class, program could create UTF-8 files without any problem.
I provide you code by 3 class files which is necessary for test:
class A0.java:
public class A0 extends A1 {
public static void main(String[] args) {
// if you want to use A1 which is extended by this class
// uncomment this two lines
// A1 run = new A1();
// run.save();
// But if you want to use A2 which isn't extended or inherited
// uncomment this lines
// A2 a2 = new A2();
// try {
// a2.create_new_file("c:/test.txt");
// a2.append_line_to_file("برنامه نویسی");
// } catch (Exception e) {
// }
// Question: Why in A1 we cannot produce properly UTF-8 text file?
}
}
class A1.java:
public class A1 extends A2{
protected void save() {
A2 a2 = new A2();
try {
a2.create_new_file("c:/test.txt");
a2.append_line_to_file("برنامه نویسی");
} catch (Exception e) {
}
}
}
class A2.java:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
public class A2 {
private BufferedWriter writer;
public void create_new_file(String file_address) throws Exception {
writer = new BufferedWriter(new FileWriter(file_address, true));
Files.newBufferedWriter(Paths.get(file_address), Charset.forName("UTF8"));
writer = new BufferedWriter(new FileWriter(file_address, true));
}
public void append_line_to_file(String line) throws IOException {
try {
writer.write(line);
writer.newLine();
writer.flush();
} catch (Exception e) {
}
}
}