Java读取文件内容与字符串保存成文件的操作

来源:互联网 发布:闪电邮 mac 编辑:程序博客网 时间:2024/05/21 11:33

因为要处理一个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文件。

源码下载

阅读全文
1 0