本文介绍了显示当前(或指定)目录中所有.txt文件的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有以下代码(从教程中无耻地复制,所以我可以得到基本的排序),它要求玩家加载他们的游戏(基于文本的冒险游戏)
但我需要一种在目录中显示所有保存的游戏的方法。我可以得到当前的目录没有后顾之忧。这是我的代码:
So I have the following code (which has been shamelessly copied from a tutorial so I can get the basics sorted), in which it asks the player to load their game (text-based adventure game)but I need a way to display all the saved games in the directory. I can get the current directory no worries. Here is my code:
public void load(Player p){
Sleep s = new Sleep();
long l = 3000;
Scanner i = new Scanner(System.in);
System.out.println("Enter the name of the file you wish to load: ");
String username = i.next();
File f = new File(username +".txt");
if(f.exists()) {
System.out.println("File found! Loading game....");
try {
//information to be read and stored
String name;
String pet;
boolean haspet;
//Read information that's in text file
BufferedReader reader = new BufferedReader(new FileReader(f));
name = reader.readLine();
pet = reader.readLine();
haspet = Boolean.parseBoolean(reader.readLine());
reader.close();
//Set info
Player.setUsername(name);
Player.setPetName(pet);
Player.setHasPet(haspet);
//Read the info to player
System.out.println("Username: "+ p.getUsername());
s.Delay(l);
System.out.println("Pet name: "+ p.getPetName());
s.Delay(l);
System.out.println("Has a pet: "+ p.isHasPet());
} catch(Exception e){
e.printStackTrace();
}
}
}
推荐答案
File currentDirectory = new File(currentDirectoryPath);
File[] saveFiles = currentDirectory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
这篇关于显示当前(或指定)目录中所有.txt文件的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!