[英]Simple issue about possible to re use java Scanner?
我还是Java的新手,是否可以重新使用Scanner对象? 下面的示例是我正在读取文件以计算字符,单词和行数。 我知道必须有一个更好的方法来仅对一个扫描仪对象进行计数,但这不是重点。 我只是想知道为什么有input.close()
但没有input.open()
或input.reset
等。由于我实际上是在读取同一文件,因此是否可以仅创建一个Scanner对象并传递3种方法使用? 谢谢
public class Test {
/**
* @throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
File file = new File("demo.java");
Scanner input = new Scanner(file);
Scanner input2 = new Scanner(file);
Scanner input3 = new Scanner(file);
int lines = 0;
int words = 0;
int characters = 0;
checkCharacters(input3);
checkLines(input);
checkwords(input2);
}
private static void checkLines(Scanner input) {
int count = 0;
while (input.hasNext()) {
String temp = input.nextLine();
String result = temp;
count++;
}
System.out.printf("%d lines \n", count);
}
private static void checkwords(Scanner input2) {
int count = 0;
while (input2.hasNext()) {
String temp = input2.next();
String result = temp;
count++;
}
System.out.printf("%d words \n", count);
}
private static void checkCharacters(Scanner input3) {
int count = 0;
while (input3.hasNext()) {
String temp = input3.nextLine();
String result = temp;
count += temp.length();
}
System.out.printf("%d characters \n", count);
}
}
不可以,无法通过扫描仪上的方法重置扫描仪。 如果您将InputStream
传递到扫描仪中,然后直接重置流,则可能可以做到这一点,但我认为这样做不值得。
您似乎要解析3次相同的文件,并处理3次相同的输入。 这似乎是在浪费处理时间。 您不能一次执行全部三个计数吗?
private static int[] getCounts(Scanner input) {
int[] counts = new int[3];
while(input.hasNextLine()){
String line = input.nextLine();
counts[0]++; // lines
counts[2]+=line.length(); //chars
//count words
//for simplicity make a new scanner could probably be better
//using regex or StringTokenizer
try(Scanner wordScanner = new Scanner(line)){
while (wordScanner.hasNext()) {
wordScanner.next();
count[1] ++; //words
}
}
}
return counts;
}
当然,面向对象的方式将是使用getNumLines()
, getNumChars()
等方法返回一个名为Counts
类的新对象。
编辑
需要注意的一件事是,我将计算与您在原始问题中所做的相同。 我不确定计数是否总是准确的,尤其是字符,因为Scanner可能不会返回所有行尾字符,因此如果连续有空白行,字符计数可能会关闭并且行数可能会关闭? 您需要对此进行测试。
不,这是不可能的,因为如文档所述
void close()
throws IOException
关闭此流并释放与其关联的所有系统资源。 如果流已经关闭,则调用此方法无效。
relaesed
resource
relaesed
,就无法取回它, relaesed
您对它的引用实际上已关闭
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.