经过一下午的努力终于实现了这个方法。
并且搞清楚了。BufferReader 的 toString() 方法,与StringBuffer 的toString()方法的不同。
两个代码如下:
import java.io.*;
class TestIO
{
public static void main(String[] args) throws Exception
{
FileReader fr=new FileReader("wo.txt");
BufferedReader br=new BufferedReader(fr);
StringBuffer buf=new StringBuffer();
int words = 0;
int ip = 0;
String ln=null;
boolean wordflag = false;
char c[]={};
while((ln=br.readLine())!=null){
buf.append(" "+ln);
String str=buf.toString();
c=str.toCharArray();
System.out.println(str);
}
for(int i=0; i<c.length; i++){
if((c[i]>='a' && c[i] <= 'z') || (c[i] >= 'A' && c[i] <= 'Z')){
if(wordflag) {
continue;
}else{
words++;
}
wordflag = true;
}else{
wordflag = false;
if(c[i] != ' ')
ip++;
}
}
System.out.println("words=" + words);
System.out.println("ip=" + ip);
}
}
import java.io.*;
class EasyString
{
public static void main(String[] args) throws Exception
{
FileReader fr=new FileReader("wo.txt");
BufferedReader br=new BufferedReader(fr);
StringBuffer buf=new StringBuffer();
String ln=null;
int words = 0;
int ip = 0;
boolean wordflag = false;
String str=br.toString();
char[] c=str.toCharArray();
System.out.println(str);
for(int i=0; i<c.length; i++){
if((c[i]>='a' && c[i] <= 'z') || (c[i] >= 'A' && c[i] <= 'Z')){
if(wordflag) {
continue;
}else{
words++;
}
wordflag = true;
}else{
wordflag = false;
if(c[i] != ' ')
ip++;
}
}
System.out.println("words=" + words);
System.out.println("ip=" + ip);
}
}
Hope you can find the difference!