How to write a UTF-8 file with Java?

前端 未结 9 1097
半阙折子戏
半阙折子戏 2020-11-22 16:17

I have some current code and the problem is its creating a 1252 codepage file, i want to force it to create a UTF-8 file

Can anyone help me with this code, as i say

相关标签:
9条回答
  • 2020-11-22 16:43

    Instead of using FileWriter, create a FileOutputStream. You can then wrap this in an OutputStreamWriter, which allows you to pass an encoding in the constructor. Then you can write your data to that inside a try-with-resources Statement:

    try (OutputStreamWriter writer =
                 new OutputStreamWriter(new FileOutputStream(PROPERTIES_FILE), StandardCharsets.UTF_8))
        // do stuff
    }
    
    0 讨论(0)
  • 2020-11-22 16:44

    Since Java 7 you can do the same with Files.newBufferedWriter a little more succinctly:

    Path logFile = Paths.get("/tmp/example.txt");
    try (BufferedWriter writer = Files.newBufferedWriter(logFile, StandardCharsets.UTF_8)) {
        writer.write("Hello World!");
        // ...
    }
    
    0 讨论(0)
  • 2020-11-22 16:45

    All of the answers given here wont work since java's UTF-8 writing is bugged.

    http://tripoverit.blogspot.com/2007/04/javas-utf-8-and-unicode-writing-is.html

    0 讨论(0)
  • 2020-11-22 16:49
    var out = new java.io.PrintWriter(new java.io.File(path), "UTF-8");
    text = new java.lang.String( src || "" );
    out.print(text);
    out.flush();
    out.close();
    
    0 讨论(0)
  • 2020-11-22 16:49

    we can write the UTF-8 encoded file with java using use PrintWriter to write UTF-8 encoded xml

    Or Click here

    PrintWriter out1 = new PrintWriter(new File("C:\\abc.xml"), "UTF-8");
    
    0 讨论(0)
  • 2020-11-22 16:54

    Below sample code can read file line by line and write new file in UTF-8 format. Also, i am explicitly specifying Cp1252 encoding.

        public static void main(String args[]) throws IOException {
    
        BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream("c:\\filenonUTF.txt"),
                "Cp1252"));
        String line;
    
        Writer out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(
                        "c:\\fileUTF.txt"), "UTF-8"));
    
        try {
    
            while ((line = br.readLine()) != null) {
    
                out.write(line);
                out.write("\n");
    
            }
    
        } finally {
    
            br.close();
            out.close();
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题