Показать имена всех документов.txt в текущем (или указанном) каталоге

Итак, у меня есть следующий код (который был бесстыдно скопирован из учебника, чтобы я мог разобраться с основами), в котором он просит игрока загрузить свою игру (текстовую приключенческую игру), но мне нужен способ отобразить все сохраненные игры в каталоге. Я не могу получить текущий каталог, не беспокойтесь. Вот мой код:

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

3 ответа

File currentDirectory = new File(currentDirectoryPath);
File[] saveFiles = currentDirectory.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
});

Вы можете сначала получить 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);   
    }
}

Это должно работать:

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 (при необходимости), чтобы копия имела указанную длину.

Другие вопросы по тегам