从Java中的位置读取文本文件

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

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风格,我需要随机访问风格。

PS数据不应该多次复制

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

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

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

 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 

你可以使用BufferedInputStream的read(byte [] b,int off,int len)

off是偏移的(从你想要开始阅读的位置)

http://docs.oracle.com/javase/7/docs/api/java/io/BufferedInputStream.html#read%28byte%5B%5D,%20int,%20int%29