Java 将 FileWriter 的编码设置为 UTF-8

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35132693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:21:02  来源:igfitidea点击:

set encoding as UTF-8 for a FileWriter

javaencodingutf-8

提问by NewToThis

Below is my code, it is intended to take two .ckl files, compare the two, add the new items and create a new merged file. The program executes correctly when run in Netbeans however, when executing the .jar the program doesn't appear to be encoding the file in UTF-8. I am rather new to programming and would like to know where or how I might need to be enforcing this encoding to take place?

下面是我的代码,它打算采用两个 .ckl 文件,比较两者,添加新项目并创建一个新的合并文件。该程序在 Netbeans 中运行时可以正确执行,但是在执行 .jar 时,该程序似乎没有以 UTF-8 对文件进行编码。我对编程很陌生,想知道我可能需要在何处或如何强制执行此编码?

** I have removed the Swing code and other lines so that only my method is shown, the method that does all of the comparing and merging.

** 我删除了 Swing 代码和其他行,以便只显示我的方法,该方法执行所有比较和合并。

public void mergeFiles(File[] files, File mergedFile) {

    ArrayList<String> list = new ArrayList<String>();

    FileWriter fstream = null;
    BufferedWriter out = null;
    try {
        fstream = new FileWriter(mergedFile, false);
        out = new BufferedWriter(fstream);
      } catch (IOException e1) {
        e1.printStackTrace();
    }
    // Going in a different direction. We are using a couple booleans to tell us when we want to copy or not. So at the beginning since we start
    // with our source file we set copy to true, we want to copy everything and insert vuln names into our list as we go. After that first file 
    // we set the boolean to false so that we dont start copying anything from the second file until it is a vuln. We set to true when we see vuln
    // and set it to false if we already have that in our list. 
    // We have a tmpCopy to store away the value of copy when we see a vuln, and reset it to that value when we see an </VULN>
    Boolean copy = true;
    Boolean tmpCopy = true;
    for (File f : files) {
        textArea1.append("merging files into: " + mergedFilePathway + "\n");
        FileInputStream fis;
        try {
            fis = new FileInputStream(f);
//                BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(mergedFile), "UTF-8"));
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));
            String aLine;
            while ((aLine = in.readLine()) != null) {
                // Skip the close checklist and we can write it in at the end
                if (aLine.trim().equals("</iSTIG>")) {
                    continue;
                }
                if (aLine.trim().equals("</STIGS>")) {
                    continue;
                }
                if (aLine.trim().equals("</CHECKLIST>")) {
                    continue;
                }
                if (aLine.trim().equals("<VULN>")) {
                    // Store our current value of copy
                    tmpCopy = copy;
                    copy = true;
                    String aLine2 = in.readLine();
                    String aLine3 = in.readLine();
                    String nameLine = in.readLine();

                    if (list.contains(nameLine.trim())) {
                        textArea1.append("Skipping: " + nameLine + "\n");
                        copy = false;
                        while (!(aLine.trim().equals("</VULN>"))) {
                            aLine = in.readLine();
                        }
                        continue; // this would skip the writing out to file part
                    } else {
                        list.add(nameLine.trim());
                        textArea1.append("::: List is now :::");
                        textArea1.append(list.toString() + "\n");
                    }
                    if (copy) {
                        out.write(aLine);
                        out.newLine();
                        out.write(aLine2);
                        out.newLine();
                        out.write(aLine3);
                        out.newLine();
                        out.write(nameLine);
                        out.newLine();
                    }
                } else if (copy) {
                    out.write(aLine);
                    out.newLine();
                }
                // after we have written to file, if the line was a close vuln, switch copy back to original value
                if (aLine.trim().equals("</VULN>")) {
                    copy = tmpCopy;
                }
            }

            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        copy = false;
    }

    // Now lets add the close checklist tag we omitted before
    try {
        out.write("</iSTIG>");
        out.write("</STIGS>");
        out.write("</CHECKLIST>");
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}                                        

采纳答案by VGR

Java has extensive, highly informative documentation. Keep it bookmarked. Refer to it first, whenever you have difficulty. You'll find it's frequently helpful.

Java 拥有大量信息丰富的文档。保留书签。遇到困难时,请先参考它。你会发现它经常有帮助。

In this case, the documentation for FileWritersays:

在这种情况下,FileWriter文档说:

The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

此类的构造函数假定默认字符编码和默认字节缓冲区大小是可接受的。要自己指定这些值,请在 FileOutputStream 上构造一个 OutputStreamWriter。

If you want to be sure your file will be written as UTF-8, replace this:

如果您想确保您的文件将被写入 UTF-8,请将其替换为:

FileWriter fstream = null;
BufferedWriter out = null;
try {
    fstream = new FileWriter(mergedFile, false);

with this:

有了这个:

Writer fstream = null;
BufferedWriter out = null;
try {
    fstream = new OutputStreamWriter(new FileOutputStream(mergedFile), StandardCharsets.UTF_8);

回答by BlueMoon93

You can just run it with the command java -Dfile.encoding=UTF-8 -jar yourjar.jar.

您可以使用命令运行它java -Dfile.encoding=UTF-8 -jar yourjar.jar

Follow thisfor more info.

按照了解更多信息。

回答by Quinn Carver

Here is a good exampleof how to construct a BufferWriter with an OutputStream that specifies UTF encoding.

这是一个很好的示例,说明如何使用指定 UTF 编码的 OutputStream 构造 BufferWriter。

回答by Saandji

For those, who use FileWriterin order to append to an existing file, the following will work

对于那些FileWriter为了附加到现有文件而使用的人,以下将起作用

try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8)) {

    //code

}