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

查看:33
本文介绍了如何使用 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 编码)

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

控制台输出:

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

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

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