2012-11-05 57 views
0

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

回答

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... 
} 
+2

更多满足您的需求,如果UFT-8,则不是:D – 2012-11-05 04:53:18

+0

@matheszabi公平点。实际要求有点模糊,因为它没有指定如何读取字符('InputStream'或'Reader')+1发表您的评论 – MadProgrammer

0

我会用一个BufferedReader读取一行。它可以是整个文件:( 但愿不是。

可以读取指定的字节数量,但如果仅仅是ASCII字符,超过此方法的可以比字符(UTF-8)

相关问题