Java读取文件

Java读取文件

 

 

  1 import java.io.BufferedReader;
  2 
  3 import java.io.File;
  4 
  5 import java.io.FileReader;
  6 
  7 import java.io.IOException;
  8 
  9 /**
 10 
 11  * 读取文件内容,这里只是将文件读取,打印出具体数据,可以根据自己的情况,修改代码
 12 
 13  * @author duyq
 14 
 15  *
 16 
 17  */
 18 
 19 public class ReadFilesTest {
 20 
 21  public static void main(String[] args) {
 22 
 23   //按行读取文件
 24 
 25   ReadFilesTest readFilesTest = new ReadFilesTest("/Users/duyq/1.txt");
 26 
 27   readFilesTest.readFileByLines();
 28 
 29  }
 30 
 31  private String filePath;//文件路径,类似(在osx:/Users/duyq/1.txt,windows:c:/duyq/1.txt)
 32 
 33  private ReadFilesTest(String filePath) {
 34 
 35   this.filePath = filePath;
 36 
 37  }
 38 
 39  /**
 40 
 41  * 按行读取文件
 42 
 43  * 
 44 
 45  * @return
 46 
 47  */
 48 
 49  public void readFileByLines() {
 50 
 51   File file = new File(this.filePath);
 52 
 53   //判断文件是否存在
 54 
 55   if (!file.exists()) {
 56 
 57    System.out.println(this.filePath + "  文件不存在。");
 58 
 59   }
 60 
 61   BufferedReader reader = null;
 62 
 63   try {
 64 
 65    reader = new BufferedReader(new FileReader(file));
 66 
 67    String tempString = "";
 68 
 69    while ((tempString = reader.readLine()) != null) {
 70 
 71     System.out.println( new String(tempString.getBytes("GBK"),"UTF-8"));
 72 
 73    }
 74 
 75    reader.close();
 76 
 77   } catch (IOException e) {
 78 
 79    e.printStackTrace();
 80 
 81    if (reader != null)
 82 
 83     try {
 84 
 85      reader.close();
 86 
 87     } catch (IOException localIOException1) {
 88 
 89     }
 90 
 91   } finally {
 92 
 93    if (reader != null)
 94 
 95     try {
 96 
 97      reader.close();
 98 
 99     } catch (IOException localIOException2) {
100 
101     }
102 
103   }
104 
105  }
106 
107 }
原文地址:https://www.cnblogs.com/XiOrang/p/9792641.html