java 用filereader怎么把一个txt文档里的单词添加到一个数组里面
要求读一个文档里面都是句子,然后把里面的单词全都读出来并且把相同的单词删掉,需要用到数组,这里是输出的例子:比如文档是这样的:Thewoodsarelovelydarka...
要求读一个文档里面都是句子,然后把里面的单词全都读出来并且把相同的单词删掉,需要用到数组,这里是输出的例子:
比如文档是这样的:The woods are lovely dark and deepBut I have promises to keepAnd miles to go before I sleepAnd miles to go before I sleep输出要求这样:
[the, woods,are,lovely,dark,and,deep,but,i,have,promises,to,keep,miles,to,go,before,sleep] 展开
比如文档是这样的:The woods are lovely dark and deepBut I have promises to keepAnd miles to go before I sleepAnd miles to go before I sleep输出要求这样:
[the, woods,are,lovely,dark,and,deep,but,i,have,promises,to,keep,miles,to,go,before,sleep] 展开
3个回答
展开全部
public class Program {
public static void main(String[] args) {
LinkedList<String> words = new LinkedList<String>();
File file = readFile("./material/ee.txt");
FileReader reader = null;
BufferedReader br = null;
String temp = "";
try {
reader = new FileReader(file);
br = new BufferedReader(reader);
while ((temp = br.readLine()) != null) {
temp = temp.toLowerCase();
String[] split = temp.trim().split(" ");
for (int i = 0; i < split.length; i++) {
if (!words.contains(split[i])) {
words.add(split[i]);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(words);
}
public static File readFile(String path) {
File file = new File(path);
if (file.exists()) {
return file;
} else
return null;
}
}
运行结果截图:
展开全部
try(Scanner scanner = new Scanner(new FileReader("word.txt"))){
ArrayList<String> words = new ArrayList<>(36);
while(scanner.hasNext()){
String word = scanner.next().toLowerCase();
if(! words.contains(word)) words.add(word);
}
System.out.println(words);
} catch (IOException e){
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
FileReader reader;
Set<String> result = new HashSet<String>() ;
char[] buffer = new char[1024];
StringBuilder sb = new StringBuilder();
while(true){
int res = reader.read(buffer);
sb.append(buffer);
if(res == -1){
...
break;
}
}
String[] words = sb.toString().split(" ");
for(String word : words){
result.add(word);
}
String[] resArr = result.toArray(new String[0]);
Set<String> result = new HashSet<String>() ;
char[] buffer = new char[1024];
StringBuilder sb = new StringBuilder();
while(true){
int res = reader.read(buffer);
sb.append(buffer);
if(res == -1){
...
break;
}
}
String[] words = sb.toString().split(" ");
for(String word : words){
result.add(word);
}
String[] resArr = result.toArray(new String[0]);
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询