1

所以我有以下代码(它是从教程中无耻地复制的,因此我可以对基础知识进行排序),其中要求玩家加载他们的游戏(基于文本的冒险游戏),但我需要一种方法来显示所有目录中保存的游戏。我可以得到当前目录,不用担心。这是我的代码:

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();
            }
            }
    }
4

3 回答 3

6
File currentDirectory = new File(currentDirectoryPath);
File[] saveFiles = currentDirectory.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
});
于 2013-06-28T22:33:00.400 回答
2

您可以先获取File目录的对象:

File ourDir = new File("/foo/bar/baz/qux/");

然后通过检查ourDir.isDirectory(),您可以确保您不会意外地尝试处理文件。您可以通过回退到另一个名称或抛出异常来处理此问题。

然后,您可以获得一个File对象数组:

File[] dirList = ourDir.listFiles();

现在,您可以使用 getName() 对它们进行迭代并执行您需要的任何操作。

例如:

ArrayList<String> fileNames=new ArrayList<>();
for (int i = 0; i < dirList.length; i++) {
    String curName=dirList[i].getName();
    if(curName.endsWith(".txt"){
        fileNames.add(curName);   
    }
}
于 2013-06-28T22:28:25.463 回答
0

这应该有效:

File folder = new File("path/to/txt/folder");
File[] files = folder.listFiles();
File[] txtFiles = new File[files.length];
int count = 0;

for(File file : files) {
    if(file.getAbsolutePath().endsWith(".txt")) {
        txtFiles[count] = file;
        count++;
    }
}

它应该是不言自明的,你只需要知道folder.listFiles()

要修剪txtFiles[]数组,请使用Array.copyOf.

File[] finalFiles = Array.copyOf(txtFiles, count);

从文档:

复制指定的数组,用 false 截断或填充(如果需要),使副本具有指定的长度。

于 2013-06-28T22:27:22.237 回答