如何使用RandomAccessFile读取UTF8编码的文件? [英] How to read UTF8 encoded file using RandomAccessFile?

查看:796
本文介绍了如何使用RandomAccessFile读取UTF8编码的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用UTF8编码的文本文件(用于特定于语言的字符)。
我需要使用RandomAccessFile来寻找特定的位置并从中读取。

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.

我想逐行阅读。

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


推荐答案

您可以使用以下代码将readLine读取的字符串转换为UTF8:

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);
}



MyFile.txt的内容:(UTF-8编码)



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

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



< h1>控制台输出:

Console output:

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

这篇关于如何使用RandomAccessFile读取UTF8编码的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆