从Java中的位置读取文本文件 [英] Read text file from position in Java

查看:360
本文介绍了从Java中的位置读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用指定的Charset从OFFSET的文本文件中读取char [](大小为COUNT)。 COUNT和OFFSET是字符,而不是字节。
他是我的代码:

I need to read char[] (size is COUNT) from text file from OFFSET with specified Charset. COUNT and OFFSET are in characters, not in bytes. He is my code:

raf = new RandomAccessFile(filePath, "r");      
if ((mBuffer == null) || (mBuffer.length < count)) {
    mBuffer = new byte[(int)(count/mDecoder.averageCharsPerByte())];
    mByteWrap = ByteBuffer.wrap(mBuffer);
    mCharBuffer = new char[count];
    mCharWrap = CharBuffer.wrap(mCharBuffer);
}
try {
    offset = (int)(offset/mDecoder.averageCharsPerByte());
    count = (int)(count/mDecoder.averageCharsPerByte());
    raf.seek(offset);
    raf.read(mBuffer,0,count);
    mByteWrap.position(0);
    mCharWrap.position(0);
    mDecoder.decode(mByteWrap, mCharWrap, true);
} catch (IOException e) {
    return null;
}
return mCharBuffer;

有没有更容易的方法? (没有手动匹配char-> byte)

我正在寻找java.util.Scanner,但它是Iterator风格,我需要随机访问 - 风格。

I was looking about java.util.Scanner, but it's Iterator-style, and i need random access-style.

PS数据不应多次复制

PS data should'n be copied many times

推荐答案

使用BufferedReader的 skip() 方法。
在你的情况下:

Use BufferedReader's skip() method. In your case:

BufferedReader reader = new BufferedReader(new FileReader(filePath));
reader.skip(n); // chars to skip
// .. and here you can start reading

如果你想指定一个你可以使用的特定编码

And if you want specify a particular encoding you can use

InputStream is = new FileInputStream(filePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
reader.skip(n); // chars to skip
// .. and here you can start reading

这篇关于从Java中的位置读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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