How to write a UTF-8 file with Java?

前端 未结 9 1311
半阙折子戏
半阙折子戏 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:56

    The Java 7 Files utility type is useful for working with files:

    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.io.IOException;
    import java.util.*;
    
    public class WriteReadUtf8 {
      public static void main(String[] args) throws IOException {
        List lines = Arrays.asList("These", "are", "lines");
    
        Path textFile = Paths.get("foo.txt");
        Files.write(textFile, lines, StandardCharsets.UTF_8);
    
        List read = Files.readAllLines(textFile, StandardCharsets.UTF_8);
    
        System.out.println(lines.equals(read));
      }
    }
    

    The Java 8 version allows you to omit the Charset argument - the methods default to UTF-8.

提交回复
热议问题