Java 按行读取文件按行写入文件并以空格分割字符串

来源:互联网 发布:free mobile java动漫 编辑:程序博客网 时间:2024/06/05 08:55

首先是按行读取字符串

import java.io.BufferedReader;import java.io.File;import java.io.FileReader;public class TxtChange {    public static void main(String[] args){          File file=new File("E:\\oldData.txt");          BufferedReader reader=null;          String temp=null;          int line=1;          try{                  reader=new BufferedReader(new FileReader(file));                  while((temp=reader.readLine())!=null){                     // System.out.println("第"+line+"行:"+temp);                    String string=AnalyzeStr.getAnalyze().getNewString(temp);//调用分割方法                    System.out.println(string);                    AnalyzeStr.getAnalyze().saveRecordInFile(string);//调用按行存储字符串                    line++;                  }          }          catch(Exception e){              e.printStackTrace();          }          finally{              if(reader!=null){                  try{                      reader.close();                  }                  catch(Exception e){                      e.printStackTrace();                  }              }          }      }  }

按照空格分割字符串并重新组合成新的字符串
空是”\s”,是转义字符,需要使用”\s”,“+”代表一个或者多个空格

public String getNewString(String fileName){        String str1="";        String str2="";        String str3="";        String []arrayStr=fileName.split("\\s+");        str1="\n\t\t"+arrayStr[0];        str2="\t"+arrayStr[1];        str3="\t"+arrayStr[2];        return str1+str2+str3;    }

然后按行保存字符串方法,path是保存的路径,例如“D://test.txt”

//追加记录    public void saveRecordInFile(String str) {        File record = new File(path);//记录结果文件        try {            if (!record.exists()) {                File dir = new File(record.getParent());                dir.mkdirs();                record.createNewFile();            }            FileWriter writer = null;            try {                // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件                writer = new FileWriter(record, true);                writer.write(str);            } catch (IOException e) {                e.printStackTrace();            } finally {                try {                    if (writer != null) {                        writer.close();                    }                } catch (IOException e) {                    e.printStackTrace();                }            }        } catch (Exception e) {            System.out.println("记录保存失败");        }    }