I want to read a file into a String in Java, x chars at a time. Then I'll do something with string, and want to continue from where I left off. How do I go about it ?
edit :
Target file is a simple text file.
解决方案
Well, firstly you need to differentiate between bytes and characters. You can read from an InputStream a certain number of bytes at a time (as a maximum number; there's no guarantee that you'll be given all the bytes that you ask for) and you can read from a Reader a number of characters at a time (again, as a maximum).
It sounds like you probably want to use an InputStreamReader around an InputStream, specifying the appropriate character encoding, and then read from the InputStreamReader. If you have to have an exact number of characters, you'd need to loop round - for example:
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);
}