我的文件夹在文件夹中。它们都包含字母和数字。例如,我的一个tex文件包含:
db: localhost
data created: 2016-01-18
user: root
pass: usbw
所以我想扫描我文件夹中的所有文件。并将每个文本文件中的信息打印到屏幕上。 到目前为止,我们试图使用这段代码:
class FileHandle {
int i;
String a;
String b;
public void openFile() throws FileNotFoundException {
File dir = new File("C:/Folder/DB");
if (dir.isDirectory()) {
for (File file : dir.listFiles()) {
Scanner s = new Scanner(file);
String f = file.getName();
System.out.println("File name:" + f);
while (s.hasNext()) {
if (s.hasNextInt()) {
i = s.nextInt();
System.out.println("int: " + i);
}
a = s.next();
b = s.next();
System.out.printf("%s", a);
System.out.printf("%s", b);
s.close();
}
}
}
}
}
但我收到了一个错误:
File name:LocalDB.txt
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Scanner.java:1070)
localhostCreated: at java.util.Scanner.hasNext(Scanner.java:1334)
at databasesearch.FileHandle.openFile(FileHandle.java:30)
at databasesearch.DatabaseSearch.main(DatabaseSearch.java:21)
C:\Users\D1sturbance\AppData\Local\NetBeans\Cache\8.1\executor- snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
答案 0 :(得分:1)
删除s.close();
或将其移至while
循环的外部。