在Netbeans中运行程序时,我可以正确显示这些字符(例如戦う)。之前,我将参数-J-Dfile.encoding = UTF-8添加到netbeans.conf文件中。
基本上,我正在创建一个程序,将数据附加到文本文件的末尾。在通过Netbeans运行时,数据将被正确保存,并且在我打开文件时会显示字符。但是,当我独立于Netbeans运行.jar(或运行内置的.exe)时,它只是将字符保存为文件“????”。
下面的代码显示了将数据附加到文件的方法。 boxValue []存储我要追加的String数据。通过Netbeans运行程序时,打开文件时文件输出将如下所示:
食べる吃 - 平原:现在たべる5食べる
在没有Netbeans的情况下独立运行程序会在文本文件中生成:
???吃 - 平原:现在??? 5 ???
private void prepareFile(String[] boxValue, boolean ruVerbIN, String addressIN){
try
{
int counter = 0;
int counter2;
if(ruVerbIN == false)
{
counter2 = 63;
}
else
{
counter2 = 55;
}
File wordFile = new File(addressIN);
FileWriter fileWriter = new FileWriter(wordFile, true);
BufferedWriter buffer = new BufferedWriter(fileWriter);
PrintWriter printWriter = new PrintWriter(buffer);
while(counter <= counter2)
{
printWriter.println(boxValue[counter]);
counter++;
}
printWriter.close();
counter = 0;
outputTextBox.setText("Export successful.");
}
catch(IOException e)
{
outputTextBox.setText("There was an error. Are you sure you entered the directory correctly? For example:" + "\n\n" + "\"C:\\\\Users\\\\Jayden\\\\Documents\\\\FLTR\\\\FLTR Data\\\\Japanese_Words.csv\"");
}
try
{
int counter = 0;
int counter2;
if(ruVerbIN == false)
{
counter2 = 63;
}
else
{
counter2 = 55;
}
File wordFile = new File(addressIN);
FileWriter fileWriter = new FileWriter(wordFile, true);
BufferedWriter buffer = new BufferedWriter(fileWriter);
PrintWriter printWriter = new PrintWriter(buffer);
while(counter <= counter2)
{
printWriter.println(boxValue[counter]);
counter++;
}
printWriter.close();
counter = 0;
outputTextBox.setText("Export successful.");
}
catch(IOException e)
{
outputTextBox.setText("There was an error. Are you sure you entered the directory correctly? For example:" + "\n\n" + "\"C:\\\\Users\\\\Jayden\\\\Documents\\\\FLTR\\\\FLTR Data\\\\Japanese_Words.csv\"");
}
答案 0 :(得分:0)
FileWriter的文档:
用于编写字符文件的便捷类。的构造者 此类假定默认字符编码和默认值 字节缓冲区大小是可以接受的。要自己指定这些值, 在OutputStreamWriter上构建FileOutputStream。
因此使用的编码取决于运行时环境。
始终明确提供编码:
try(OutputStream out = new FileOutputStream(file);
Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8) {
// I/O
} catch (IOException e) {
// error handling
}
答案 1 :(得分:0)
您是否尝试在程序中再次阅读该文件?在Windows机器上,默认编码是CP-1252而不是UTF-8。
您还可以将BufferedWriter与给定的字符集
一起使用FileWriter fw = new FileWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
或使用Java7
Charset charset = Charset.forName("UTF-8"); BufferedWriter writer = Files.newBufferedWriter(p.resolve("foo.txt"), charset)