希望每次退出while循环时,readLine重新定位到文件的第一行,也就是说从新搜索一边文件。请高手给看看下边的程序问题出在那里了,找了半天没找出什么原因,很郁闷!谢谢
int length=0;
int app=0;
String str;
StringBuffer sub=new StringBuffer();
for (int i = 65; i < 91; i++) {
for (int j = 65; j < 91; j++) {
sub.append( (char) i);
sub.append( (char) j);
FileReader fr = new FileReader("d:\\test.txt");
BufferedReader read = new BufferedReader(fr);
while ( (str = read.readLine()) != null) {
for (int ii = 0; ii < str.length() - 1; ii++) {
if (str.substring(ii, ii + 2).equals(sub.toString()) == true) {
app++;
} //end if } //end for
} //end while
System.out.println("app(" + sub + ")=" + app );
sub.delete(0, 2);
app = 0;
read=null;
fr.close(); continue; } //end inner for
} //end outter for
int length=0;
int app=0;
String str;
StringBuffer sub=new StringBuffer();
for (int i = 65; i < 91; i++) {
for (int j = 65; j < 91; j++) {
sub.append( (char) i);
sub.append( (char) j);
FileReader fr = new FileReader("d:\\test.txt");
BufferedReader read = new BufferedReader(fr);
while ( (str = read.readLine()) != null) {
for (int ii = 0; ii < str.length() - 1; ii++) {
if (str.substring(ii, ii + 2).equals(sub.toString()) == true) {
app++;
} //end if } //end for
} //end while
System.out.println("app(" + sub + ")=" + app );
sub.delete(0, 2);
app = 0;
read=null;
fr.close(); continue; } //end inner for
} //end outter for
ABAACADAA
ADDACAAAD目的就是想检测到AA~ZZ在文件中出现的次数。
public static void main(String[] args) throws FileNotFoundException, IOException {
int app = 0;
String str;
int idx = 0; FileReader fr = new FileReader("test.txt");
BufferedReader read = new BufferedReader(fr);
while ((str = read.readLine()) != null) {
while ((idx = str.indexOf("AA", idx)) > 0) {
idx++;
app++;
}
while ((idx = str.indexOf("ZZ", idx)) > 0) {
idx++;
app++;
}
}
System.out.println(app);
}
}以上代码经过测试。
import java.util.*;public class TT {
private File file;
private Map<String,Counter> map;
public TT(File f){
file = f;
map = new HashMap<String,Counter>();
}
public void scan()throws IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line = new String();
while((line=br.readLine())!=null){
int i=0;
while(i<line.length()-1){
String tmp = line.substring(i,i+2);
if(map.containsKey(tmp)){
map.get(tmp).add();
}
else{
map.put(tmp,new Counter());
}
i += 1;
}
}
}
public void show(){
Set entryset = map.entrySet();
Iterator it = entryset.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
public static void main(String args[])throws IOException{
TT tt = new TT(new File("d:\\test.txt"));
tt.scan();
tt.show();
}
}//---------------------
class Counter{
int c;
public Counter(){
c=1;
}
public void add(){
c++;
}
public int getCounter(){
return c;
}
public String toString(){
return Integer.toString(c);
}
}
BufferedReader read = new BufferedReader(fr);
写在了for循环里,当然每次循环都重新读一次文件了,没重读一次文件当然也就重新定位一次了。