Java – how to use RandomAccessFile to read utf8 encoded files?

I have text files encoded in utf8 (for language specific characters)

I want to read line by line

String str = myreader.readLine(); //returns wrong text,not decoded 
String str myreader.readUTF(); //An exception occurred: java.io.EOFException

Solution

You can convert stringline readLine to utf8 using the 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);
}

MyFile. Txt: (UTF-8 code)

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

Console output:

Line: ÐÑÐ¸Ð²ÐµÑ Ð¸Ð· УкÑаинÑ
UTF8: Привет из Украины
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>