1

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();
            }
            }
    }
Steve P.
  • 14,489
  • 8
  • 42
  • 72
Aeolos
  • 11
  • 4

3 Answers3

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");
    }
});
MaxAlexander
  • 460
  • 3
  • 10
2

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);   
    }
}
nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

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.

Rob
  • 88
  • 1
  • 14
  • 1
    While valid this may leave a good gap in the array. Perhaps use an arrayList or other composite type instead? – nanofarad Jun 28 '13 at 22:29
  • @hexafraction `count` was meant to be included in the `if` statement, this shouldn't leave any gaps. Thanks for pointing it out, I've edited it now. Edit: Unless you mean nulls after all the values in which case yes an ArrayList would be better, but I guess OP is quite new to Java and he might want to keep in simple in which case a simple array should suffice. – Rob Jun 28 '13 at 22:31
  • No, the problem is that txtFiles is being made with a length made to store ALL the files in the folder, while it should only accommodate the txt files themselves. – nanofarad Jun 28 '13 at 22:33
  • @hexafraction Yes, true, I'll alter my answer. – Rob Jun 28 '13 at 22:36