我正在尝试创建一个 Java 琐事应用程序,该应用程序从给定文件夹中的单独问题文件中读取琐事。我的想法是使用 FileHandler 类中的 run() 方法将文件夹中的每个文本文件设置为字典,并为它们提供整数键,以便我可以轻松地随机化它们在游戏中出现的顺序。我找到了一段简单的代码,它能够遍历文件夹并获取每个文件的路径,但以 Path 类的形式。我需要字符串类形式的路径(或只是名称)。因为我稍后需要将它们转换为文件类(除了字符串构造函数,而不是路径)。这是遍历文件夹的代码块:
public class FileHandler implements Runnable{
static Map<Integer, Path> TriviaFiles; //idealy Map<Integer, String>
private int keyChoices = 0;
public FileHandler(){
TriviaFiles = new HashMap<Integer, Path>();
}
public void run(){
try {
Files.walk(Paths.get("/home/chris/JavaWorkspace/GameSpace/bin/TriviaQuestions")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
TriviaFiles.put(keyChoices, filePath);
keyChoices++;
System.out.println(filePath);
}
});
} catch (FileNotFoundException e) {
System.out.println("File not found for FileHandler");
} catch (IOException e ){
e.printStackTrace();
}
}
public static synchronized Path getNextValue(){
return TriviaFiles.get(2);
}
}
Run Code Online (Sandbox Code Playgroud)
还有另一个名为 TextHandler() …