在这个例子中,我们将看到如何使用FileInputStream和BufferedInputStream在 Java 中读取文件。以下是我们在下面的代码中采取的详细步骤:
1)通过在创建文件对象期间提供文件的完整路径(我们将读取)来创建File实例。
2)将文件实例传递给FileInputStream,它打开与实际文件的连接,该文件由文件系统中的File对象文件命名。
3)将FileInputStream实例传递给BufferedInputStream ,它创建BufferedInputStream并保存其参数,即输入流,供以后使用。创建内部缓冲区数组并将其存储在buf中,使用该数组,读取操作可提供良好的性能,因为内容在缓冲区中很容易获得。
4)用于循环读取文件。方法available()用于检查文件的结尾,因为当指针到达文件末尾时返回 0。使用FileInputStream的read()方法读取文件内容。
package beginnersbook.com;import java.io.*;public class ReadFileDemo { public static void main(String[] args) { //Specify the path of the file here File file = new File("C://myfile.txt"); BufferedInputStream bis = null; FileInputStream fis= null; try { //FileInputStream to read the file fis = new FileInputStream(file); /*Passed the FileInputStream to BufferedInputStream *For Fast read using the buffer array.*/ bis = new BufferedInputStream(fis); /*available() method of BufferedInputStream * returns 0 when there are no more bytes * present in the file to be read*/ while( bis.available() > 0 ){ System.out.print((char)bis.read()); } }catch(FileNotFoundException fnfe) { System.out.println("The specified file not found" + fnfe); } catch(IOException ioe) { System.out.println("I/O Exception: " + ioe); } finally { try{ if(bis != null && fis!=null) { fis.close(); bis.close(); } }catch(IOException ioe) { System.out.println("Error in InputStream close(): " + ioe); } } } }
