第三步:编写测试类TestTxt.java的代码:
import java.io.*;public class Test { //获取txt文件的内容,并删除空格返回新的内容 public static String openReader(String fileUrl) { BufferedReader br=null; StringBuffer sb=new StringBuffer(); try { br=new BufferedReader( new FileReader(new File(fileUrl))); String temp=" "; while((temp=br.readLine())!=null){ if(temp.trim().equals("")){ continue; } sb.append(temp); } br.close(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } //覆盖旧文件的内容 public static void write(String fixedText) { BufferedWriter bw=null; try { bw=new BufferedWriter(new FileWriter(new File("D:\\1.txt"))); bw.write(fixedText); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(bw!=null){ try { bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static void main(String[] args) { write(openReader("D:\\1.txt")); }}