# 如何在 Java 中读取文件 - BufferedInputStream > 原文: [https://beginnersbook.com/2014/01/how-to-read-file-in-java-bufferedinputstream/](https://beginnersbook.com/2014/01/how-to-read-file-in-java-bufferedinputstream/) 在这个例子中,我们将看到如何使用`FileInputStream`和`BufferedInputStream`在 Java 中读取文件。以下是我们在下面的代码中采取的详细步骤: 1)通过在创建文件对象期间提供文件的完整路径(我们将读取)来创建 File 实例。 2)将文件实例传递给 [FileInputStream](https://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html#FileInputStream(java.io.File)) ,它打开与实际文件的连接,该文件由文件系统中的 File 对象文件命名。 3)将`FileInputStream`实例传递给 [BufferedInputStream](https://docs.oracle.com/javase/7/docs/api/java/io/BufferedInputStream.html#BufferedInputStream(java.io.InputStream)) ,它创建`BufferedInputStream`并保存其参数,即输入流,供以后使用。创建内部缓冲区数组并将其存储在 buf 中,使用该数组,读取操作可提供良好的性能,因为内容在缓冲区中很容易获得。 4)用于循环读取文件。方法 [available()](https://docs.oracle.com/javase/7/docs/api/java/io/BufferedInputStream.html#available())用于检查文件的结尾,因为当指针到达文件末尾时返回 0。使用`FileInputStream`的 [read()](https://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html#read())方法读取文件内容。 ```java 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); } } } } ```