I am currently needing to load the contents of a folders filenames to an arraylist I have but I am unsure as how to do this.
To put it into perspective I have a folder with One.txt, 开发者_如何学CTwo.txt, Three.txt etc. I want to be able to load this list into an arraylist so that if I was to check the arraylist its contents would be :
arraylist[0] = One
arraylist[1] = Two
arraylist[3] = Three
If anyone could give me any insight into this it would be much appreciated.
Here's a solution that uses java.io.File.list(FilenameFilter)
. It keeps the .txt
suffix; you can strip these easily if you really need to.
File dir = new File(".");
List<String> list = Arrays.asList(dir.list(
new FilenameFilter() {
@Override public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
}
));
System.out.println(list);
File dir = new File("/some/path/name");
List<String> list = new ArrayList<String>();
if (dir.isDirectory()) {
String[] files = dir.list();
Pattern p = Pattern.compile("^(.*?)\\.txt$");
for (String file : files) {
Matcher m = p.matcher(file);
if (m.matches()) {
list.add(m.group(1));
}
}
}
You can try with
File folder = new File("myfolder");
if (folder.isDirectory())
{
// you can get all the names
String[] fileNames = folder.list();
// you can get directly files objects
File[] files = folder.listFiles();
}
Here's My answer, I've used this before personally to get all the filenames,
to be used in a loadsave function in one of my games.
public void getFiles(String path){
//Put filenames in arraylist<string>
File dir = new File(path);
ArrayList<String> filenames = new ArrayList<String>();
for(File file : dir.listFiles()){
savefiles.add(file.getName());
}
//Check if the files are in the arraylist
for (int i = 0; i < savefiles.size(); i++){
String s = savefiles.get(i);
System.out.println("File "+i+" : "+s);
}
System.out.println("\n");
}
I hope that may have been of use to you C: - Hugs rose
See the Jave File API, particularly the list() function.
File my_dir = new File("DirectoryName");
assert(my_dir.exists()); // the directory exists
assert(my_dir.isDirectory()); // and is actually a directory
String[] filenames_in_dir = my_dir.list();
Now filenames_in_dir
is an array of all the filenames, which is almost precisely what you want.
If you want to strip the extensions off the individual filenames, that's basic string handling - iterate over the filenames and take care of each one.
Have a look at java.io.File it gives you all the control you may need. Here is a URL for it http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html
精彩评论