一、FileInputStream概览
FileInputStream是Java IO库中为读取文件提供的一种输入流,可以用来读取文件中的字节数据。FileInputStream会默认以字节的形式读取文件数据,它包含了多个构造函数以方便开发者进行使用。
下面是一个简单的文件读取示例:
File file = new File("test.txt"); FileInputStream fis = new FileInputStream(file); int ch; while((ch = fis.read()) != -1) { System.out.print((char)ch); } fis.close();
这段代码首先创建了一个File对象,并指定它要读取的文件名为test.txt,接着创建了一个FileInputStream对象,并将File对象作为参数传入构造函数中。通过调用FileInputStream的read()方法,可以不断读取文件的字节数据并将其打印到控制台上。
二、FileInputStream的常用方法
FileInputStream提供了多个常用方法,下面简单介绍几个。
1. read()
FileInputStream的read()方法可以读取一个字节的数据,并返回一个int类型的字符,如果已经读取到文件结尾,则返回-1。例如:
FileInputStream fis = new FileInputStream("test.txt"); int ch = fis.read(); System.out.println((char)ch); fis.close();
这段代码将读取test.txt文件的第一个字节,将其转换成字符类型后打印到控制台上。
2. available()
FileInputStream的available()方法可以获取文件还未读取的字节数,例如:
FileInputStream fis = new FileInputStream("test.txt"); System.out.println(fis.available()); fis.close();
这段代码将打印出文件test.txt中还未读取的字节数。
3. skip()
FileInputStream的skip()方法可以跳过指定的字节数,例如:
FileInputStream fis = new FileInputStream("test.txt"); fis.skip(10); int ch; while((ch = fis.read()) != -1) { System.out.print((char)ch); } fis.close();
这段代码将跳过test.txt文件的前10个字节,然后读取剩下的字节数据并打印到控制台上。
三、关闭FileInputStream
当我们完成对文件数据的读取后,必须关闭FileInputStream以释放资源。关闭流的操作非常简单,只需要调用FileInputStream的close()方法即可:
FileInputStream fis = new FileInputStream("test.txt"); // do some operations fis.close();
如果在操作过程中出现了异常,也同样需要保证FileInputStream被正确关闭。这里我们可以使用try-catch-finally语句来确保FileInputStream能够被正常关闭:
FileInputStream fis = null; try { fis = new FileInputStream("test.txt"); // do some operations } catch (IOException e) { e.printStackTrace(); } finally { if(fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } }
四、总结
FileInputStream是Java IO库中为读取文件提供的一种输入流,它提供了多个方法可以方便开发者进行文件读取操作。使用时需要注意关闭流以释放资源。
原创文章,作者:QABY,如若转载,请注明出处:https://www.506064.com/n/149451.html