我有3个班来处理所有配置。 (2级2000行)
我希望在不编写0的所有代码的情况下添加对UTF-8字符的支持; /
我展示了我最小的课程(没有完成,我不想用1400行垃圾邮件:)) 实际上只有两个变量:
package com.gmail.bukkitSmerf.professionalWarns;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
public class LangHandler {
private static String lWarns_DeletedWarnAddon, lWarns_ExpiredWarnAddon;
public static String getlWarns_DeletedWarnAddon() {
return lWarns_DeletedWarnAddon;
}
public static String getlWarns_ExpiredWarnAddon() {
return lWarns_ExpiredWarnAddon;
}
public void createConfig(boolean forceConfigUpdate) {
try {
String langFileName = "languageEN.yml";
InputStream input = ProfessionalWarns
.getPluginResource_languageEN();
if (ConfigHandler.getcGeneral_Language().equalsIgnoreCase("PL")) {
langFileName = "languagePL.yml";
input = ProfessionalWarns.getPluginResource_languagePL();
}
File langFile = new File(ProfessionalWarns.getPluginDataFolder(),
langFileName);
if (!langFile.exists()) {
langFile.getParentFile().mkdirs();
ConfigHandler.copy(input, langFile);
}
YamlConfiguration lang = new YamlConfiguration();
FileConfiguration rawLang = YamlConfiguration
.loadConfiguration(input);
lang.load(langFile);
lWarns_DeletedWarnAddon = lang.getString("Warns.DeletedWarnAddon",
rawLang.getString("Warns.DeletedWarnAddon"));
lWarns_ExpiredWarnAddon = lang.getString("Warns.ExpiredWarnAddon",
rawLang.getString("Warns.ExpiredWarnAddon"));
if (ConfigHandler.iscGeneral_AutoUpdateConfigs()
|| forceConfigUpdate) {
FileWriter fw = new FileWriter(langFile);
PrintWriter pw = new PrintWriter(fw);
pw.flush();
pw.write("Warns:\n DeletedWarnAddon: '"
+ lWarns_DeletedWarnAddon + "'\n ExpiredWarnAddon: '"
+ lWarns_ExpiredWarnAddon + "'");
pw.close();
}
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
ProfessionalWarns
.logWarning("Error when trying create/write/reload language file!");
}
}
}
我不知道如何在这里使用UTF-8。
我也不想删除任何功能。
如果可以,请给我一些关于该代码的建议:)
//对不起我的英文
答案 0 :(得分:0)
根据您的评论,我将责怪您使用FileWriter
:
FileWriter fw = new FileWriter(langFile);
这取决于您安装的默认编码,我愿意打赌不是UTF-8。您可以通过以下方式验证:
System.out.println(Charset.defaultCharset());
无论如何,将UTF-8字符写入文件的正确方法是使用OutputStreamWriter
:
FileOutputStream fos = new FileOutputStream("your_file");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
PrintWriter pw = new PrintWriter(osw);
除非这是一次性代码,否则您应关闭FileOutputStream
块中的finally
。