遍历文件夹中的文件 对话框选择文件 案例 制作chm文件时用的一个小程序

//遍历文件夹进行替换
package com.mengdian.findandreplace.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class FindAndReplaceService {
	/**
	 * 
	 * @param file
	 *  需要进行替换的文件或文件夹递归替换
	 * @return
	 * @throws Exception
	 */
	public static boolean replace(File file) throws Exception {
		if (file.isDirectory()) {// 如果是目录则得到他的子文件进行替换操作
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				replace(files[i]);
			}
			return false;
		} else {
			searchAndReplace(file);
			return true;
		}
	}

	/**
	 * 
	 * @param file要替换的目标文件
	 * @return
	 * @throws Exception
	 */
	public static boolean searchAndReplace(File file) throws Exception{
		String fileName = file.getName();
		//只需要对.html后缀的文件进行操作,不是.html的文件则直接跳出
		if(!fileName.contains(".html")){
			return true;
		}
//		if(fileName.contains(".jpg")||fileName.contains(".png")||fileName.contains(".gif")){
//			return false;
//		}
		
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"gb2312"));
		StringBuffer sb = new StringBuffer();
		String str = null;
		while(null != (str = br.readLine())){
			sb.append(str);
		}
		
		String des = sb.toString();
		//追加让html不能右键不能复制的功能
		des = des.replace("<body>", "<body οncοntextmenu='return false' οndragstart='return false' leftMargin=0 topMargin=0 οncοpy='return false' oncut='return false'>");
		des = des.replace("<body >", "<body οncοntextmenu='return false' οndragstart='return false' leftMargin=0 topMargin=0 οncοpy='return false' oncut='return false'>");
		//给body加上距顶和距左边距
		des = des.replace("leftMargin=0", "leftMargin=10");
		des = des.replace("topMargin=0", "topMargin=10");
		des = des.replace("<img width=124 height=77 src=\"$main.files/image004.png\" alt=DL></span><span lang=EN-US style='font-size:16.0pt;font-family:黑体'>ICS27.100</span></p><p class=MsoNormal style='line-height:26.0pt'><span lang=EN-USstyle='font-size:16.0pt;font-family:黑体'>P61</span></p><p class=MsoNormal style='line-height:26.0pt'><span style='font-size:16.0pt;font-family:黑体'>备案号:<span lang=EN-US>J195</span>—<span lang=EN-US>2002</span></span></p>", "");
//		System.out.println(des);
		String result1 = des.replace("http://www.Word2ChmOnline.com","");
		String result_des = result1.replace("此文档由DeBin软件生成。", "");
		String result_des2 = result_des.replace("<b><span style='font-family:宋体'>详情请参见系统查阅标准模块</span></b>", "<span style='font-family:宋体'>详情请参见系统查阅标准模块</span>");
		result_des2 = result_des2.replace("<b><span style='font-size:13.5pt;font-family:宋体'>请参考系统查阅标准</span></b>", "<span style='font-family:宋体'>详情请参见系统查阅标准模块</span>");
		result_des2 = result_des2.replace("<b><span style='font-size:13.5pt;font-family:宋体'>请参考系统</span></b><b><span style='font-size:13.5pt;font-family:宋体'>查阅</span></b><b><span style='font-size:13.5pt;font-family:宋体'>标准</span></b>", "<span style='font-family:宋体'>详情请参见系统查阅标准模块</span>");
		result_des2 = result_des2.replace("<b><span style='font-size:13.5pt;font-family:宋体'>请参考</span></b><b><span style='font-size:13.5pt;font-family:宋体'>系统</span></b><b><span style='font-size:13.5pt;font-family:宋体'>查阅标准</span></b>", "<span style='font-family:宋体'>详情请参见系统查阅标准模块</span>");
		result_des2 = result_des2.replace("<b>详情请参见系统查阅标准模块</b>", "详情请参见系统查阅标准模块");
		result_des2 = result_des2.replace("<b><span style='font-family:宋体'>详情请参见系统查阅标准模块</span></b>","<span style='font-family:宋体'>详情请参见系统查阅标准模块</span>");
		//替换文件中的@符号为""
		result_des2 = result_des2.replaceAll("[@]", "");
		br.close();
		String filePath = file.getAbsolutePath();
		filePath = filePath.replaceAll("[@]", "");
		File file2 = new File(filePath);
		file.renameTo(file2);
		FileOutputStream fos = new FileOutputStream(file2);
		PrintWriter pw = new PrintWriter(new OutputStreamWriter(fos, "gb2312"));
		pw.write(result_des2);
		pw.close();
		fos.close();
		return true;
	}

	/**
	 * 对视图层关闭按钮的处理
	 * @param frame
	 */
	public void exit(JFrame frame) {
		int val = JOptionPane.showConfirmDialog(frame, "确定离开吗?");
		if (val == JOptionPane.YES_OPTION) {
			System.exit(0);
		}
	}
}
//选择文件对话框
 package com.mengdian.findandreplace.ui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.mengdian.findandreplace.service.FindAndReplaceService;

public class FindAndReplaceFrame extends JFrame {
    private String filePath = null;
    
    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    public FindAndReplaceFrame(){
        init();
    }
    
    /**
     * 初始化界面方法
     */
    private void init()    {
        //窗口标题
        this.setTitle("批量对文件进行查找替换");
        //设置大小
        this.setSize(800,500);
        //剧中
        this.setLocationRelativeTo(null);
        //加组件
        this.setContentPane(createContentPanel());
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        //点击关闭按钮退出程序
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
                super.windowClosing(e);
            }
        });
    }
    /**
     * 创建主窗口
     * @return
     */
    private JPanel createContentPanel() {
        JPanel panel = new JPanel(new FlowLayout(100,200,10));
        final JTextField jtf = new JTextField("-------------------------文件绝对路径-------------------------");
        jtf.setEditable(false);
        JButton jbt = new JButton("选择文件/文件夹");
        panel.add(jtf,BorderLayout.CENTER);
        
        panel.add(jbt,BorderLayout.SOUTH);
        jbt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser jfc = new JFileChooser();
                jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int returnVal = jfc.showOpenDialog(jfc);
                if(returnVal == JFileChooser.APPROVE_OPTION){
                    filePath = jfc.getSelectedFile().getAbsolutePath();
                    jtf.setText(filePath);
                    File file = new File(filePath);
                    try {
                        FindAndReplaceService.replace(file);
                        //弹出替换成功对话框
                        JOptionPane.showConfirmDialog(FindAndReplaceFrame.this, "替换成功","消息",JOptionPane.CLOSED_OPTION);
                        //点击确定按钮推出
                    } catch (Exception ee) {
                        JOptionPane.showConfirmDialog(FindAndReplaceFrame.this, "替换失败");
                        ee.printStackTrace();
                    }
                }
            }
        });
        return panel;
    }
}

//主程序
package com.mengdian.findandreplace.test;

import com.mengdian.findandreplace.ui.FindAndReplaceFrame;

public class Main {
    public static void main(String[] args) {
        FindAndReplaceFrame frame = new FindAndReplaceFrame();
        frame.setVisible(true);
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值