How to read UTF8 encoded file using RandomAccessFile?

前端 未结 8 2122
深忆病人
深忆病人 2020-12-06 05:35

I have text file that was encoded with UTF8 (for language specific characters). I need to use RandomAccessFile to seek specific position and read from.

I want rea

8条回答
  •  天命终不由人
    2020-12-06 05:59

    You can convert string, read by readLine to UTF8, using following code:

    public static void main(String[] args) throws IOException {
        RandomAccessFile raf = new RandomAccessFile(new File("MyFile.txt"), "r");
        String line = raf.readLine();
        String utf8 = new String(line.getBytes("ISO-8859-1"), "UTF-8");
        System.out.println("Line: " + line);
        System.out.println("UTF8: " + utf8);
    }
    

    Content of MyFile.txt: (UTF-8 Encoding)

    Привет из Украины
    

    Console output:

    Line: ÐÑÐ¸Ð²ÐµÑ Ð¸Ð· УкÑаинÑ
    UTF8: Привет из Украины
    

提交回复
热议问题