How to write a UTF-8 file with Java?

前端 未结 9 1098
半阙折子戏
半阙折子戏 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<String> lines = Arrays.asList("These", "are", "lines");
    
        Path textFile = Paths.get("foo.txt");
        Files.write(textFile, lines, StandardCharsets.UTF_8);
    
        List<String> 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.

    0 讨论(0)
  • 2020-11-22 16:57

    Try this

    Writer out = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream("outfilename"), "UTF-8"));
    try {
        out.write(aString);
    } finally {
        out.close();
    }
    
    0 讨论(0)
  • 2020-11-22 17:02

    Try using FileUtils.write from Apache Commons.

    You should be able to do something like:

    File f = new File("output.txt"); 
    FileUtils.writeStringToFile(f, document.outerHtml(), "UTF-8");
    

    This will create the file if it does not exist.

    0 讨论(0)
提交回复
热议问题