How to read and write UTF-8 to disk on the Android?

后端 未结 5 788
余生分开走
余生分开走 2020-12-16 02:58

I cannot read and write extended characters (French accented characters, for example) to a text file using the standard InputStreamReader methods shown in the Android API ex

相关标签:
5条回答
  • 2020-12-16 03:20

    Very simple and straightforward. :)

    String filePath = "/sdcard/utf8_file.txt";
    String UTF8 = "utf8";
    int BUFFER_SIZE = 8192;
    
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), UTF8),BUFFER_SIZE);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), UTF8),BUFFER_SIZE);
    
    0 讨论(0)
  • 2020-12-16 03:30

    if you face any such kind of problem try doing this. You have to Encode and Decode your data into Base64. This worked for me. I can share the code if you need it.

    0 讨论(0)
  • 2020-12-16 03:30

    Check the encoding of your file by right clicking it in the Project Explorer and selecting properties. If it's not the right encoding you'll need to re-enter your special characters after you change it, or at least that was my experience.

    0 讨论(0)
  • 2020-12-16 03:32

    this should just work on Android, even without explicitly specifying UTF-8, because the default charset is UTF-8. if you can reproduce this problem, please raise a bug with a reproduceable test case here:

    http://code.google.com/p/android/issues/entry

    0 讨论(0)
  • 2020-12-16 03:33

    When you instantiate the InputStreamReader, use the constructor that takes a character set.

    InputStreamReader tmp = new InputStreamReader(in, "UTF-8");
    

    And do a similar thing with OutputStreamWriter

    I like to have a

    public static final Charset UTF8 = Charset.forName("UTF-8");
    

    in some utility class in my code, so that I can call (see more in the Doc)

    InputStreamReader tmp = new InputStreamReader(in, MyUtils.UTF8);
    

    and not have to handle UnsupportedEncodingException every single time.

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