Java.io.FileInputStream.read() 方法
描述
java.io.FileInputStream.read() 从这个输入流中读取一个字节的数据。 如果没有可用的输入,该方法将阻塞。
声明
以下是 java.io.FileInputStream.read() 方法的声明 −
public int read()
参数
NA
返回值
这些方法返回下一个数据字节,如果到达文件末尾,则返回 -1。
异常
IOException − 如果发生 I/O 错误
示例
下面的例子展示了 java.io.FileInputStream.read() 方法的使用。
package com.tutorialspoint;
import java.io.IOException;
import java.io.FileInputStream;
public class FileInputStreamDemo {
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
int i = 0;
char c;
try {
// create new file input stream
fis = new FileInputStream("C://test.txt");
// read till the end of the file
while((i = fis.read())!=-1) {
// converts integer to character
c = (char)i;
// prints character
System.out.print(c);
}
} catch(Exception ex) {
// if any error occurs
ex.printStackTrace();
} finally {
// releases all system resources from the streams
if(fis!=null)
fis.close();
}
}
}
假设我们有一个文本文件c:/test.txt,其内容如下。 该文件将用作我们示例程序的输入 −
ABCDEF
让我们编译并运行上面的程序,这将产生下面的结果 −
ABCDEF

