文件操作,在java中很常用,對於存在特定編碼的文件,則需要根據字符編碼進行讀取,要不容易出現亂碼
1 /** 2 * 讀取文件 3 * @param filePath 文件路徑 4 */ 5 public static void readFile(String filePath) { 6 FileInputStream fis = null; 7 BufferedReader br = null; 8 9 String line = null; 10 try { 11 fis = new FileInputStream(filePath); 12 br = new BufferedReader(new InputStreamReader(fis)); 13 while (null != (line = br.readLine())) { 14 System.out.println(line); 15 } 16 } catch (FileNotFoundException e) { 17 e.printStackTrace(); 18 } catch (IOException e) { 19 e.printStackTrace(); 20 } finally { 21 // 釋放資源 22 if (null != fis) { 23 try { 24 fis.close(); 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } 28 } 29 if (null != br) { 30 try { 31 br.close(); 32 } catch (IOException e) { 33 e.printStackTrace(); 34 } 35 } 36 } 37 }
使用字符編碼讀取文件,防止亂碼
1 /** 2 * 讀取文件,使用字符編碼讀取文件,防止亂碼 3 * 字符編碼參數如果為空或者null,則使用默認讀取文件 4 * 5 * @param filePath 文件路徑 6 * @param encodingStr 字符編碼 7 */ 8 public static void readFile(String filePath, String encodingStr) { 9 if (null == encodingStr || encodingStr.trim().length() <= 0) { 10 readFile(filePath); 11 } else { 12 FileInputStream fis = null; 13 BufferedReader br = null; 14 15 String line = null; 16 try { 17 fis = new FileInputStream(filePath); 18 // 使用字符編碼讀取文件,防止亂碼 19 br = new BufferedReader(new InputStreamReader(fis, encodingStr)); 20 while (null != (line = br.readLine())) { 21 System.out.println(line); 22 } 23 } catch (FileNotFoundException e) { 24 e.printStackTrace(); 25 } catch (IOException e) { 26 e.printStackTrace(); 27 } finally { 28 // 釋放資源 29 if (null != fis) { 30 try { 31 fis.close(); 32 } catch (IOException e) { 33 e.printStackTrace(); 34 } 35 } 36 if (null != br) { 37 try { 38 br.close(); 39 } catch (IOException e) { 40 e.printStackTrace(); 41 } 42 } 43 } 44 } 45 46 }