0

如何逐步读取文本文件的 20 个字符,例如,如果我有一个函数 read_next,第一次调用它会返回字符串中的前 20 个字符,第二次调用它会返回接下来的 20 个字符文件。请注意,我不想将整个文件读入数组然后将其分解。

4

2 回答 2

1

基本上,你想使用InputStream#read(byte[])

从输入流中读取一些字节并将它们存储到缓冲区数组 b. 实际读取的字节数以整数形式返回

public int read(InputStream is, byte[] bytes) throws IOException {
    return is.read(bytes);
}

然后你基本上想调用这个方法......

byte[] bytes = new byte[20];
int bytesRead = -1;
while ((bytesRead = read(is, bytes)) != -1) {
    // Process the bytes..
    // Note, while bytes.length will always == 20
    // there will only ever be bytesRead worth of 
    // values in the array
}

更新

在一些不错的反馈之后,您还可以使用相同的想法将相同的想法应用于 UFT-8 编码文件Reader

public int read(Reader reader, char[] chars) throws IOException {
    return reader.read(chars);
}

并调用该方法......

Reader reader = new InputStreamReader(new FileInputStream("file"), "UTF-8");
char[] chars = new char[20];
int charsRead = -1;
while ((charsRead = read(reader, chars)) != -1) {
    // Process chars, the same caveats apply as above...
}
于 2012-11-05T04:50:30.693 回答
0

我会用 BufferedReader 读一行。它可以是整个文件:(希望不是。

您可以读取指定数量的字节,但这些可以超过字符(utf-8)

于 2012-11-05T04:51:18.950 回答