java - 如何从文本文件中读取x个字符

标签 java

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

最佳答案

基本上,您想使用InputStream#read(byte[])

Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer

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

关于java - 如何从文本文件中读取x个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13226028/

相关文章:

java - hadoop - map reduce 任务和静态变量

java - 导航不适用于 struts 2

java - Android 应用程序中的 If/Else 验证?

java - null 真的很特别吗?

java - Spring 安全 : hasAuthority is ignored when configured globally for HttpSecurity

java - jar 文件无法正常工作 java.lang.NoClassDefFoundError

Java等待变量改变

java - 如何在嵌套列表上使用 groupingBy

java - Spring的依赖注入(inject)不会破坏信息隐藏吗?

java - 如何从程序的输出中删除错误?