//评测题目: 请用JAVA实现一个通用文本处理组件, 输入为一文本文件,实现对文件内容进行处理,处理时不关注处理顺序,处理逻辑可能为比如将文件内容复制,打印,翻译等等, 要求尽可能高单进程处理性能,扩展性以及通用性,对于新的处理需求可以低成本实现
// 文件读取接口及实现类
interface Reader{
byte\[\] read\(\);
}
public class FileReader implements Reader{
private File file;
public FileReader\(File file\){
this.file = file;
}
@Overidd
byte\[\] read\(\){
// 读取文件转换成字节
}
}
// 输出写入接口及实现类
interface Writer{
void wirte\(\);
}
public class ConsoleWriter implements Writer{
private String result;
public ConsoleWriter(String result){
this.result = result;
}
@Overidd
void write(){
System.out.println\(result\);
}
}
// 几个处理的hander
interface Handler{
String handle\(byte\[\] bytes\);
}
public class copyHandler implements Handler{
private String result;
@Overidd
String handle(byte[] bytes){
// 复制文件内容 result = "copy txt";
result = new String\(bytes\);
return “copy”;
}
}
// 这部分考虑NIO
public class TextServer{
private ExecutorService executor;
private Map<String,Handler> handlers;
private List<String> keys;
public TextServer\(int size\){
executor = Executors.newFixedThreadPool\(size\);
}
public addHandler\(String key,Handler handler\){
handlers.put\(key,handler\);
}
public String run\(\){
while\(!Thread.interrupted\(\)\(\)&&CollectionUtils.isNotEmpty\(keys\)\){
// 迭代handlers,如果有handler,并且处理完数据的
for\(int i=0;i<keys.size\(\);i++\){
Handler handler = handlers.get\(key\);
if\("print".equals\(key\)\){
Writer writer = new ConsoleWriter\(hander.getResult\(\)\);
writer.write\(\);
}
keys.remove\(key\);
}
}
}
public void handle\(byte\[\] bytes\){
Hander hander;
Iterator it = handlers.entrySet\(\).iterator\(\);
while\(it.hasNext\(\)\){
Map.Entry<String,Handler> entry = it.next;
hander = entry.getValue\(\);
Runable runable = new Runable\(\){
public void run\(\){
// handler方法里面执行的是比较耗时的操作,不过这是另开的线程不影响其他handler
String key = hander.handle\(bytes\);
keys.add\(key\);
}
// submit也可以只是一个有返回值一个没有
executor.execute\(runable\);
}
}
}
public class Test{
public static void main\(String\[\] args\){
TextServer server = new TextServer\(10\);
server.addHandler\("copy",copyHandler\);
FileReader reader = new FileReader\(new File\("路径"\)\);
server.handle\(reader.read\(\)\);
server.run\(\);
}
public class Main{
public static void main(String[] args){
String doubleString = "123.45";
System.out.println\(string2Double\(doubleString\)\);
}
private static double string2Double(String str){
if\(null == str\|\|str.equals\(""\)\){
throw new Exception\("input string can not be null"\);
}
// 一些非法字符暂时忽略
// 整体思路如果有.则代表有分割,前面的整数统计位数,小数部分也一样,然后\*10,\*100相加,得到最终结果
int dotPosition;
int length = str.length;
for\(int i=0,i<length;i++\){
if\(".".equals\(str.charAt\(i\)\)\){
dotPostion=i;
break;
}else if\("-".equals\(str.charAt\(i\)\)\)
}
int intSum;
int priseSum;
for\(int i=0;i<length;i++\){
if\(i<dotPostion\){
// 下面这个^应该不能这么用。。
intSum+=\(str.charAt\(i\)-"0"\)\*10^\(dotPostion-i\);
}else{
priseSum+=\(str.charAt\(i\)-"0"\)/Math.pow\(10,\(i-dotPostion\)\);
}
}
// double = Double.valueOf\(doubleString\);
return intSum+priceSum;
}
}
}
}