一、首先要搞定的东西
首先我需要搞定的是文件的读取以及将读取到的数据带格式的整个放到另一个文件的功能。首先,请看代码。
package service;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStreamWriter;
import strategy.Change;
public class FileHelper {
private File rFile;
private File wFile;
private BufferedReader br;
private BufferedWriter bw;
private Change change;
private String wUrl = System.getProperty("user.dir") + "\\src\\temp\\temp";
public FileHelper(File rFile,Change change) throws FileNotFoundException {
this.rFile = rFile;
this.wUrl += rFile.getName().substring(rFile.getName().lastIndexOf("."));
this.wFile = new File(wUrl);
System.out.println("生成文件路径: " + wUrl);
this.br = new BufferedReader(new InputStreamReader(new FileInputStream(this.rFile)));
this.bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this.wFile)));
this.change = change;
}
public void exceute() throws IOException{
String str = null;
while ((str = this.br.readLine()) != null) {
this.bw.write(this.change.change(str));
this.bw.newLine();
this.bw.flush();
}
this.br.close();
this.bw.close();
}
}
这里我创建了带有Field类和Change类的FileHelper构造方法,并提供了exceute来执行整个转换操作。
exceute方法中的主要操作就是一个while 循环,实现带格式输出回去的主要代码就两行。没毛病,读一行写一行,写完之后换行,就跟自己敲代码的时候一样。
this.bw.newLine();
this.bw.flush();
二、随后要搞定的东西
随后我需要搞定的就是TP转换算法的植入,毕竟我目前做的东西只是个复读机。
上一步我创建了带有Change类的构造方法,通过构造方法将同一个算法家族Change下的TPChange传入,并且通过调用Change接口规定的change方法将每一行读取的字符串进行转换并写入到目标文件下。也就是src目录下temp包中的temp文件
this.bw.write(this.change.change(str));
private String wUrl = System.getProperty("user.dir") + "\\src\\temp\\temp";
通过实现Change接口的方式编写出一系列的转换算法,在使用时只需实例化一个需要的Change并传入到FileHelper中,就可以完全不影响原有代码的前提下完成不一样的功能,采用策略模式的好处就在这里了。
接下来创建TPChange类并实现Change接口,根据整个算法的业务逻辑完善TPChange类的change方法。它的代码可以是这样的
package strategy;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TPChange implements Change {
private String tag_match[] =new String[]{//需要替换的html标签数组,需要用到的时候补充
"else/","/if"
};
private HashMap<String, String> mathod_match;
public TPChange(JTextArea showArea) {//添加显示效果的构造方法
this.mathod_match = new HashMap<>();
this.mathod_match.put("{:U", "{:url");
this.mathod_match.put("{:M", "{:model");
this.show_area = showArea;
}
public TPChange() {
this.mathod_match = new HashMap<>();
this.mathod_match.put("{:U", "{:url");
this.mathod_match.put("{:M", "{:model");
}
@Override
public String change(String target) {
target = filterMathod(target, mathod_match);//匹配方法
target = fiterHtmlSpecialTag(target,"if");//匹配特殊html标签
target = fiterHtmlNormTag(target,tag_match);//匹配一般html标签
return target;
}
/**
* 用来替换更新后的方法字符串
* @param target
* @param map
* @return
*/
public String filterMathod(String target,Map<String, String> map) {
String k = null;
String v = null;
for(Map.Entry<String, String> entry:map.entrySet()){
k = entry.getKey();
v = entry.getValue();
if (target.indexOf(k) != -1) {
target = target.replace(k, v);
System.out.println("method替换结果为: \n"+target+"\n");
show(show_area, "method替换结果为: \n"+target+"\n");
}
}
return target;
}
/***
* 用来替换匹配到的特殊html标签
* @param str
* @param tag
* @return
*/
public String fiterHtmlSpecialTag(String str, String tag) {
String regxp = "<\\s*" + tag + "\\s+([^>]*)\\s*>";
Pattern pattern = Pattern.compile(regxp);
Matcher matcher = pattern.matcher(str);
StringBuffer sb = new StringBuffer(str.length());
String n_String = "";
String re_String = "";
int end = 0;
while (matcher.find()){
re_String ="{"+tag+" "+matcher.group(1)+"}";
n_String =matcher.quoteReplacement(re_String);//去除转义字符
matcher.appendReplacement(sb, n_String);
end = matcher.end();//记录最后一次匹配的end节点数
}
if (!sb.toString().isEmpty()) {
String reString = sb.toString()+str.substring(end);//把匹配好的字符串加上原字符串的余式
System.out.println(tag+"替换结果为: \n"+reString+"\n");
show(show_area, tag+"替换结果为: \n"+reString+"\n");
return reString;
}else {
return str;
}
}
/***
* 用来替换匹配到的一般html标签
* @param str
* @param match
* @return
*/
public String fiterHtmlNormTag(String str,String[] match) {
String regxp = "<([^>]*)>"; // 过滤所有以<开头以>结尾的标签
Pattern pattern = Pattern.compile(regxp);
Matcher matcher = pattern.matcher(str);
StringBuffer sb = new StringBuffer(str.length());
String n_String = "";
String re_String = "";
int end = 0;
while (matcher.find()){
for (int i = 0; i < match.length; i++) {
if (matcher.group(1).equals(match[i])) {
re_String ="{"+matcher.group(1)+"}";
n_String =matcher.quoteReplacement(re_String);//去除转义字符
matcher.appendReplacement(sb, n_String);
end = matcher.end();//记录最后一次匹配的end节点数
}
}
}
if (!sb.toString().isEmpty()) {
String reString = sb.toString()+str.substring(end);//把匹配好的字符串加上原字符串的余式
System.out.println("tag"+"替换结果为: \n"+reString+"\n");
show(show_area, "tag"+"替换结果为: \n"+reString+"\n");
return reString;
}else {
return str;
}
}
}
三、最后要做的东西
搞定了烦人的算法以后,我还需要做的就是在客户端调用这两个类,从而完成这个小工具的编写。代码如下
package view;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import service.FileHelper;
import strategy.BaseTPChange;
import strategy.TPChange;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
public class SUView extends JFrame {
private JPanel contentPane;
JTextArea textArea = new JTextArea();
JButton btnTp = new JButton("TP3.2转为5.0");
JButton button_1 = new JButton("取回文件");
JButton button = new JButton("上传文件");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SUView frame = new SUView();
frame.setTitle("SU");
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SUView() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel.add(button);
btnTp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File rFile = new File(System.getProperty("user.dir")+"\\src\\temp\\picture_material.html");
TPChange tpChange = new TPChange(textArea);
try {
FileHelper helper = new FileHelper(rFile, tpChange);
helper.exceute();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
panel.add(btnTp);
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel.add(button_1);
contentPane.add(textArea, BorderLayout.CENTER);
}
}
emmmm,代码太长,不看。其实核心的代码就这么几条
File rFile = new File(System.getProperty("user.dir")+"\\src\\temp\\picture_material.html");
TPChange tpChange = new TPChange(textArea);
try {
FileHelper helper = new FileHelper(rFile, tpChange);
helper.exceute();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
首先实例化一个file,这里我选择的是一个之前写的包含了一些3.2代码风格的html文件。
随后实例化一个TPChange
最后把他们俩放到FileHelper
调用exceute方法。。。。。
整个小工具到此结束。今天又是元气满满的一天啊。ahhhhh
网友评论