【发布时间】:2016-01-05 16:52:25
【问题描述】:
我已经测试了生成 UTF-8 文本文件的最佳和更安全的方法,但是当我在多个 抽象类 中使用它时,它会生成 ANSI 格式 文件不是 UTF-8 格式! 有什么错误或什么可以防止它吗? 同样,我的代码是正确的,当我将所有代码放在一个类中时,程序可以毫无问题地创建 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) {
}
}
}
【问题讨论】:
-
如果代码没有产生正确的输出,它显然是不正确的。但如果不实际展示,其他人就不可能知道问题所在。
-
欢迎来到 SO。请访问help center 并阅读How to Ask。您没有提供任何具体信息,因此任何人都无法帮助您。就目前而言,这个问题是题外话,很可能很快就会结束。此外,在说明 Java 系统中存在错误时要非常小心。虽然确实存在许多错误,但 99% 的问题是用户对问题的误解。
-
这是一个技术问题,但我尽量尽快提供代码。
-
现在它已经准备好了,你可以看到我在代码中问了什么!
标签: java inheritance utf-8 io ansi