此文源码主要为应用 Java 读取文本文件内容实例的源代码。若有不足之处,敬请大神指正,不胜感激!
第一种:文本文件写入,若文件存在则删除原文件,并重新创建文件。源代码如下所示:
1 /** 2 * @function 文本文件操作:写入数据 3 * 4 * @author Aaron.ffp 5 * @version V1.0.0: autoUISelenium main.java.aaron.java.tools FileUtils.java txtWrite, 2015-2-2 21:03:53 Exp $ 6 * 7 * @param filename :文本文件全路径 8 * @param encoding :编码格式 9 * @param fileContent :写入内容 10 * 11 * @return boolean 写入成功返回true 12 * 13 * @throws IOException 14 */ 15 public boolean txtWrite(String filename, String encoding, String fileContent){ 16 // 先读取源文件内容, 再进行写入操作 17 boolean flag = false; 18 19 FileInputStream fis = null; 20 InputStreamReader isr = null; 21 BufferedReader br = null; 22 FileOutputStream fos = null; 23 PrintWriter pw = null; 24 25 /* 创建文件(删除旧文件) */ 26 if (!this.createFile(filename)) { 27 return flag; 28 } 29 30 try{ 31 File file = new File(filename); // 文件路径 32 33 if(file.isFile()){ 34 // 将文件读入输入流 35 fis = new FileInputStream(file); 36 isr = new InputStreamReader(fis); 37 br = new BufferedReader(isr); 38 39 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file), encoding); 40 BufferedWriter bw = new BufferedWriter(osw); 41 bw.write(fileContent); 42 bw.close(); 43 44 flag = true; 45 }else{ 46 this.message = "文件全路径非法。当前文件全路径为:" + filename; 47 this.logger.warn(this.message); 48 } 49 }catch(Exception ioe){ 50 this.message = "写文件{" + filename + "}内容出错。" + ioe.getMessage(); 51 this.logger.error(this.message); 52 }finally{ 53 try { 54 if(pw != null){ 55 pw.close(); 56 } 57 if(fos != null){ 58 fos.close(); 59 } 60 if(br != null){ 61 br.close(); 62 } 63 if(fis != null){ 64 fis.close(); 65 } 66 } catch (Exception e) { 67 this.message = e.getMessage(); 68 this.logger.error(this.message); 69 } 70 } 71 72 return flag; 73 }