我已经测试了最好、更安全的生产方式
UTF-8型
文本文件,但当我在多个文件中使用它时
抽象类
,它生产
ANSI格式
文件不是UTF-8格式!
有什么bug或什么东西可以阻止它吗?
同样,我的代码是正确的,当我将所有代码放在一个类中时,程序可以创建
UTF-8型
文件没有任何问题。
我通过测试所需的3个类文件为您提供代码:
类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?
}
}
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) {
}
}
}
类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) {
}
}
}