簡體   English   中英

如何從文本文件中讀取x個字符

[英]How to read x amount of characters from a text file

如何逐步讀取文本文件的20個字符,例如,如果我有一個read_next函數,第一次調用它將返回字符串中的前20個字符,第二次調用將返回字符串中的后20個字符文件。 請注意,我不想將整個文件讀入數組然后分解。

基本上,您想使用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
}

更新

得到一些好評后,您還可以使用Reader將相同的想法應用於UFT-8編碼的文件

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

我會用BufferedReader讀一行。 它可以是整個文件:(希望不是。

您可以讀取指定數量的字節,但這些字節可以超過字符數(utf-8)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM