玖叶教程网

前端编程开发入门

FileInputStream流详解(fileinputstream的方法)

1、FileInputStream概念

FileInputStream流被称为文件字节输入流,意思指对文件数据以字节的形式进行读取操作如读取图片视频等;


2、我们看JDK对FileInputStream描述

  • FileInputStream从文件系统中的文件获取输入字节。 什么文件可用取决于主机环境。
  • FileInputStream用于读取诸如图像数据的原始字节流。 要阅读字符串,请考虑使用FileReader 。

3、构造方法摘要

1、FileInputStream(File file):通过打开与实际文件的连接创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。

2、FileInputStream(FileDescriptor fdObj)创建 FileInputStream通过使用文件描述符 fdObj ,其表示在文件系统中的现有连接到一个实际的文件。

3、FileInputStream(String name)通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。


4、通过FileInputStream读取D盘中的 hi.txt 文件

/**
    第一种方式:使用 read()方法
    1、read()方法每次只读取一个字节
    2、read()方法返回值是一个int类型,代码该字符的int值
    3、如果返回值为-1,说明读取完毕
*/
public class $Test03 {
	
	public static void main(String[] args) throws Exception {
		
		String path = "D:\\hi.txt";
		InputStream inputStream = null;
		try {
			inputStream = new FileInputStream(path);
			int resultData;
			while ((resultData = inputStream.read()) != -1) {
				System.out.print((char)resultData);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			inputStream.close();
		}
	}
}

/**
	使用read(byte[] b)方法读取文件
  1、byte[] b = new byte[3];代表一次性去读三个字节方法b数组中
  2、read(byte[] b)方法的返回值是读取的字节的长度

*/
	public static void main(String[] args) throws Exception {
		
		String path = "D:\\hi.txt";
		InputStream inputStream = null;
		byte[] b = new byte[3];
		try {
			inputStream = new FileInputStream(path);
			int resultLength;
			while ((resultLength = inputStream.read(b)) != -1) {
				System.out.print(new String(b , 0 , resultLength));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			inputStream.close();
		}
	}
}

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言