我如何一次读取文件x字节?在java中

Shr*_*ath 0 java file

我想在Java中读取一个文件到一个字符串,一次是x个字符.然后我会用字符串做一些事情,并希望从我离开的地方继续.我该怎么办呢?

编辑:

目标文件是一个简单的文本文件.

Jon*_*eet 7

那么,首先需要区分字节字符.您可以一次读取InputStream一定数量的字节(作为最大数字;不能保证您将获得所需的所有字节),并且您可以一次从Reader多个字符中读取(再次,作为最大值).

这听起来像你可能想使用一个InputStreamReader围绕InputStream,指定相应的字符编码,然后从读取InputStreamReader.如果你必须有一个确切数量的字符,你需要循环 - 例如:

public static String readExactly(Reader reader, int length) throws IOException {
    char[] chars = new char[length];
    int offset = 0;
    while (offset < length) {
        int charsRead = reader.read(chars, offset, length - offset);
        if (charsRead <= 0) {
            throw new IOException("Stream terminated early");
        }
        offset += charsRead;
    }
    return new String(chars);
}
Run Code Online (Sandbox Code Playgroud)