package com.***.helper;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
/**
* http://bbs.csdn.net/topics/390998324?page=1#post-398977511<br>
* 假设要读取一个TXT文件 内容包括各种括号 逗号 斜杠 “--” 数字 和单词 <br>
* 但只取单词 并 存进 arraylist <br>
* 文件来源:http://www.k8.hk/1.txt
*
* @author ***
* @date 2015年3月14日 下午7:41:12
*/
public class ReadWords {
public static void main(String[] args) throws IOException {
String fileName = "/Users/***/workspace/***_demo/***/src/main/java/com/***/helper/1.txt";
List<String> lines = FileUtils.readLines(new File(fileName));
List<String> result = analysisWords(lines);
FileUtils.writeLines(new File(fileName + ".result"), result);
}
public static List<String> analysisWords(List<String> lines) {
List<String> result = new ArrayList<String>();
for (String line : lines) {
List<String> tmp = analysisWords(line);
result.addAll(tmp);
}
return result;
}
public static List<String> analysisWords(String line) {
List<String> result = new ArrayList<String>();
String r = "";
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
// 不是字母,清空缓存(当前单词);是字母,继续追加当前单词
if (!isLetter(c)) {
// 过滤空白字符串
if (r.trim().length() > 0) {
result.add(r);
}
r = "";
} else {
r += c;
}
}
return result;
}
private static boolean isLetter(char c) {
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
return true;
} else {
return false;
}
}
}
浙公网安备 33010602011771号