1. 程式人生 > >Java 按行讀取檔案按行寫入檔案並以空格分割字串

Java 按行讀取檔案按行寫入檔案並以空格分割字串

首先是按行讀取字串

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("記錄儲存失敗");
        }
    }