如何一次读取文件x字节?在java中 [英] How do I read file x bytes at a time ? in java
问题描述
我想将文件读入Java的String中,一次x个字符.然后,我将对字符串进行一些操作,并希望从我停下来的地方继续.我该怎么办?
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 ?
目标文件是一个简单的文本文件.
Target file is a simple text file.
推荐答案
首先,您需要区分 bytes 和 characters .您可以一次从InputStream
读取一定数量的字节(作为最大数量;不能保证将获得所需的所有字节),并且可以从Reader
读取一个数量一次(最多,最多)个字符.
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).
听起来像您可能想要在InputStream
周围使用InputStreamReader
,指定适当的字符编码,然后从InputStreamReader
中读取.如果必须有确切个字符,则需要循环-例如:
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);
}
这篇关于如何一次读取文件x字节?在java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!