How do I read file x bytes at a time ? in java
I want to read a file into a String in Java, x chars at a time. Then I'll do some开发者_开发百科thing 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);
}
Have you tried using BufferedReader? It defines read(char[], int, int)
that does pretty much exactly what you want. That is, it recursively calls read in an attempt to fill the buffer.
Example usage:
char[] chars = new char[length];
reader.read(chars,0,length);
String str = String.valueOf(chars);
Documentation:
public int read(char[] cbuf, int off, int len) throws IOException
This method implements the general contract of the corresponding read method of the Reader class. As an additional convenience, it attempts to read as many characters as possible by repeatedly invoking the read method of the underlying stream. This iterated read continues until one of the following conditions becomes true:
- The specified number of characters have been read,
- The read method of the underlying stream returns -1, indicating end-of-file, or
- The ready method of the underlying stream returns false, indicating that further input requests would block.
If the first read on the underlying stream returns -1 to indicate end-of-file then this method returns -1. Otherwise this method returns the number of characters actually read.
The last point is important as it means that streams that can block might return with less characters than expected. Though when reading from a local file a reader or stream should always have bytes available to read.
精彩评论