用BufferReader读取了一个文件,希望将其中所有的单词放入一个数组,但是空行总是被当作一个字符串,请问如何处理
如果读入文件的内容是:apple banana
cabbage
我希望输出的结果是:
apple banana cabbage
总共3个单词
但是我现在得到的结果总是:
apple banana cabage 总共4个单词
请问如何处理?小妹拜谢各位了!!!
代码如下:
import java.io.*;
public class Readertest0{
public static void main(String []args) throws IOException{
File sourceFile = new File("C:\\Documents and Settings\\Administrator\\桌面\\x.txt");
if(!sourceFile.exists()){
System.out.println(" Source file doesn't exist");
System.exit(0);
}
else{
FileInputStream fileInputStream = new FileInputStream("C:\\Documents and Settings\\Administrator\\桌面\\x.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader br = new BufferedReader(inputStreamReader);
String s = " ";
StringBuffer sb = new StringBuffer();
String lineSparator = System.getProperty("line.sparator");
while((s = br.readLine())!=null){
sb.append(s).append(lineSparator);
}
br.close();
String s1 = sb.toString().trim();
String[] tokens = s1.split("[^a-zA-Z]+|null|\\r|\\n");
int i = tokens.length;
for (int n = 0;n <= i-1;n++){
System.out.print(tokens[n] + " ");
}
System.out.print("总共" + i +"个单词");
}
}
}
--------------------编程问答-------------------- data.txt里面是你的文件内容
apple banana
cabbage
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("data.txt"));
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
}
}
输出(中间的回车,空格都去掉了):
apple
banana
cabbage --------------------编程问答-------------------- 我不是想单纯得到一个输出结果,而是想把所有的单词都放入一个数组,然后要对这个数组作进一步处理,所以不能用scanner……在我的代码的基础上应该做些什么修改呢?谢谢! --------------------编程问答--------------------
Scanner scanner = new Scanner(new File("data.txt"));--------------------编程问答-------------------- 过滤空行,空格 --------------------编程问答-------------------- String 类有个trim()方法是去掉首尾空格的,可以用这个
List<String> contents = new ArrayList<String>();
while (scanner.hasNext()) {
contents.add(scanner.next());
}
String[] filecontents = contents.toArray(new String[0]);
补充:Java , Eclipse