83.md 2.9 KB
Newer Older
W
wizardforcel 已提交
1
# 如何在 Java 中读取文件 - `BufferedInputStream`
W
java  
wizardforcel 已提交
2 3 4 5

> 原文: [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 中读取文件。以下是我们在下面的代码中采取的详细步骤:
W
wizardforcel 已提交
6

W
wizardforcel 已提交
7
1)通过在创建文件对象期间提供文件的完整路径(我们将读取)来创建`File`实例。
W
wizardforcel 已提交
8

W
wizardforcel 已提交
9
2)将文件实例传递给[`FileInputStream`](https://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html#FileInputStream(java.io.File)),它打开与实际文件的连接,该文件由文件系统中的`File`对象文件命名。
W
wizardforcel 已提交
10

W
wizardforcel 已提交
11
3)将`FileInputStream`实例传递给[`BufferedInputStream`](https://docs.oracle.com/javase/7/docs/api/java/io/BufferedInputStream.html#BufferedInputStream(java.io.InputStream)) ,它创建`BufferedInputStream`并保存其参数,即输入流,供以后使用。创建内部缓冲区数组并将其存储在`buf`中,使用该数组,读取操作可提供良好的性能,因为内容在缓冲区中很容易获得。
W
wizardforcel 已提交
12

W
wizardforcel 已提交
13
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())方法读取文件内容。
W
java  
wizardforcel 已提交
14

W
wizardforcel 已提交
15
```java
W
java  
wizardforcel 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
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);
              }         
        }
   }    
}
```