1. 程式人生 > >Java讀取檔案內容與字串儲存成檔案的操作

Java讀取檔案內容與字串儲存成檔案的操作

因為要處理一個txt文字,將裡面的手機號複製出來,由於內容比較多也比較亂,一個一個找太費時間,就寫了個下面的程式

直接貼程式碼

讀取檔案內容轉為字串

package com.sh.tool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 讀取檔案內容
 * ClassName: ReadTxtFile 
 * @Description
: TODO * @author micoMo * @date 2017-8-21 */
public class ReadTxtFile { public static String readTxtFile(String filePath){ String txtStr = "";//儲存檔案內容 try { File file=new File(filePath); if(file.isFile() && file.exists()){ InputStreamReader isr = new
InputStreamReader(new FileInputStream(file),"GBK"); BufferedReader br = new BufferedReader(isr); String line = null; StringBuffer bf = new StringBuffer(); //逐行讀取檔案內容 while((line = br.readLine()) != null){ //正則表示式匹配手機號
if(line.length()>0){ Pattern pattern = Pattern.compile("(1|861)(3|5|7|8)\\d{9}$*"); Matcher matcher = pattern.matcher(line); while (matcher.find()) { //拼接獲取的手機號 bf.append(matcher.group()).append("\n"); } } } txtStr = bf.toString().replaceAll("((\r\n)|\n)[\\s\t ]*(\\1)+", "$1");//去掉多餘的空行 isr.close(); } else { System.out.println("沒有找到該檔案"); } } catch (Exception e) { e.printStackTrace(); } finally { } return txtStr; } }

將字串儲存到指定檔案

package com.sh.tool;

import java.io.File;
import java.io.PrintWriter;
import javax.swing.filechooser.FileSystemView;

/**
 * 將字串儲存成檔案
 * ClassName: SaveTxtFile 
 * @Description: TODO
 * @author micoMo
 * @date 2017-8-21
 */
public class SaveTxtFile{

    public static void main(String args[]) throws Exception{

        FileSystemView fsv = FileSystemView.getFileSystemView();

        File com = fsv.getHomeDirectory();//獲取桌面路徑

        String filePath = com.getPath() + "/read.txt";//指定要讀取檔案read.txt的路徑(桌面)

        String str = ReadTxtFile.readTxtFile(filePath);//讀取read.txt檔案輸出字串

        File f = new File(com.getPath() + "/save.txt");//建立儲存檔案save.txt(桌面)

        PrintWriter pw = new PrintWriter(f);

        pw.print(str);//將字串寫入到save.txt

        pw.close();
    }

}

檔案可以是txt word excel檔案。

原始碼下載