【发布时间】:2016-01-21 00:43:26
【问题描述】:
我的文本文件在一个文件夹中。它们都包含字母和数字。例如,我的 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)
【问题讨论】:
-
我缩进了你的代码。现在您应该更容易看到问题了。
标签: java file-io text-files