gpt4 book ai didi

java - 从多个文本文件中读取数据

转载 作者:行者123 更新时间:2023-12-01 10:34:00 25 4
gpt4 key购买 nike

我的文本文件位于文件夹中。它们都包含字母和数字。例如我的 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)

最佳答案

删除s.close();或将其移至while循环之外。

关于java - 从多个文本文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34913437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com