文件操作,在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 }