Aeolos
Aeolos

Reputation: 11

Display the names of all .txt documents within the current (or specified) directory

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

Upvotes: 1

Views: 149

Answers (3)

Rob
Rob

Reputation: 98

This should work:

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++;
    }
}

It should be pretty self explanatory, you just need to know folder.listFiles().

To trim down the txtFiles[] array use Array.copyOf.

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

From the docs:

Copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.

Upvotes: 0

MaxAlexander
MaxAlexander

Reputation: 560

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

Upvotes: 6

nanofarad
nanofarad

Reputation: 41281

You can first get a File object for the directory:

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

Then by checking ourDir.isDirectory() you can make sure you don't accidentally try to work on a file. You can handle this by falling back to another name, or throwing an exception.

Then, you can get an array of File objects:

File[] dirList = ourDir.listFiles();

Now, you may iterate through them using getName() for each and do whatever you need.

For example:

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

Upvotes: 2

Related Questions