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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10102703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:38:12  来源:igfitidea点击:

Read text file from position in Java

javatextio

提问by styanton

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:

我需要从具有指定字符集的 OFFSET 的文本文件中读取 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;

Is there any way easier ? (without manual matching char->byte)

有没有更简单的方法?(无需手动匹配 char->byte)

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

我正在寻找 java.util.Scanner,但它是迭代器风格的,我需要随机访问风格。

PS data should'n be copied many times

PS数据不应该被多次复制

采纳答案by dash1e

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

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

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

回答by Amit

you can use read(byte[] b, int off, int len) of BufferedInputStream

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

here the off is offset (point from where you want to start reading)

这里关闭是偏移量(从你想开始阅读的点)

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

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