BufferedReader指针 [英] BufferedReader pointer
问题描述
我有以下代码,但我不明白如何将指针重置为起始位置:
I have the following code but I don't understand how I can reset the pointer to the starter position:
BufferedReader inp=new BufferedReader(new FileReader(file));
Scanner leggi=new Scanner(inp);
for(int i=0;i<nwords;i++){
while(leggi.hasNext())
if(leggi.next().equals(args[i+2]))
occorrenze[i]=occorrenze[i]+1;
}
inp.close();
我尝试过
inp.mark(0);
inp.reset();
没有结果。
推荐答案
Paul,
我建议您通读以下旧主题: Java BufferedReader返回文本文件的顶部吗?。
I suggest you read through this old thread: Java BufferedReader back to the top of a text file?.
我个人更喜欢Jon Skeet的回答,归结为不要麻烦[除非您必须]。
Personally I prefer Jon Skeet's response, which boils down to "Don't bother [unless you MUST]."
干杯。基思。
编辑:另外,即使您点击了,也应该始终关闭该输入文件异常。 最终
块对此非常合适。
Also you should ALLWAYS close that input file, even if you hit an Exception. The finally
block is perfect for this.
EDIT2:
希望您仍然与我们在一起。
Hope you're still with us.
这是我的尝试,FWIW ,则无需重置输入文件,只需为循环转置
while
和。
Here's my attempt, and FWIW, you DON'T need to reset the input-file, you just need to transpose your while
and for
loops.
package forums;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WordOccurrenceCount
{
public static void main(String[] args) {
try {
String[] words = { "and", "is", "a", "the", "of", "as" };
int[] occurrences = readOccurrences("C:/tmp/prose.txt", words);
for ( int i=0; i<words.length; i++ ) {
System.out.println(words[i] + " " + occurrences[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static final int[] readOccurrences(String filename, String... words)
throws IOException
{
int[] occurrences = new int[words.length];
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filename));
Scanner scanner = new Scanner(reader);
while ( scanner.hasNext() ) {
String word = scanner.next();
for ( int i=0; i<words.length; i++ ) {
if ( words[i].equals(word) ) {
occurrences[i]++;
}
}
}
} finally {
if(reader!=null) reader.close();
}
return occurrences;
}
}
和 BTW , java.util.Map 非常适合构建频率表... 并行数组仅仅是90年代。 Map的默认实现是 HashMap
类...默认情况下,我的意思是在需要Map时使用HashMap,除非您有充分的理由使用某些东西否则,这种情况不会经常发生。 HashMap通常是表现最好的全能工具。
And BTW, java.util.Map is perfect for building a frequency table... Parallel arrays are just SOOOOO 90's. The "default" implementation of Map is the HashMap
class... By default I mean use HashMap whenever you need a Map, unless you've got a good reason to use something else, which won't be often. HashMap is generally the best allround performer.
这篇关于BufferedReader指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!