Java使用FileInputStream流读取文件的示例详解

分类:知识百科 日期: 点击:0

Java使用FileInputStream流读取文件

FileInputStream类是一种可以从文件中读取字节的输入流,它的构造函数有两种:

  • FileInputStream(String filePath):以文件路径的形式构建FileInputStream对象
  • FileInputStream(File file):以文件对象的形式构建FileInputStream对象

FileInputStream类的read()方法可以读取文件中的字节,其返回值是读取的字节,如果到达文件末尾,则返回-1。

使用示例

下面给出一个使用FileInputStream类读取文件的示例:

public static void readFile(String filePath) {
	FileInputStream fis = null;
	try {
		// 以文件路径的形式构建FileInputStream对象
		fis = new FileInputStream(filePath);
		// 定义一个变量存储读取到的字节
		int b;
		// 使用循环来读取文件中的字节
		while ((b = fis.read()) != -1) {
			// 打印读取到的字节
			System.out.print((char) b);
		}
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		// 关闭FileInputStream
		if (fis != null) {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

上面的示例中,使用构造函数FileInputStream(String filePath)构建FileInputStream对象,使用read()方法读取文件中的字节,关闭FileInputStream。

使用FileInputStream类可以很方便的读取文件中的字节,只需要构造FileInputStream对象,使用read()方法即可,记得关闭FileInputStream。

标签:

版权声明

1. 本站所有素材,仅限学习交流,仅展示部分内容,如需查看完整内容,请下载原文件。
2. 会员在本站下载的所有素材,只拥有使用权,著作权归原作者所有。
3. 所有素材,未经合法授权,请勿用于商业用途,会员不得以任何形式发布、传播、复制、转售该素材,否则一律封号处理。
4. 如果素材损害你的权益请联系客服QQ:77594475 处理。