I want to use
File f = new File(\"C:\\\\\");
to make an ArrayList with the contents of the folder.
I am not very good with buffered
Streams are fast and very easy to read:
final Path rootPath = Paths.get("/tmp");
// All entries Path objects
ArrayList<Path> all = Files
.list(rootPath)
.collect(Collectors.toCollection(ArrayList::new));
// Only regular files at Path objects
ArrayList<Path> regularFilePaths = Files
.list(rootPath)
.filter(Files::isRegularFile)
.collect(Collectors.toCollection(ArrayList::new));
// Only regular files as String paths
ArrayList<String> regularPathsAsString = Files
.list(rootPath)
.filter(Files::isRegularFile)
.map(Path::toString)
.collect(Collectors.toCollection(ArrayList::new));
If you want to retrieve all the files recursively, you can do something like below
public class FileLister {
static List<String> fileList = new ArrayList<String>();
public static void main(String[] args) {
File file = new File("C:\\tmp");
listDirectory(file);
System.out.println(fileList);
}
public static void listDirectory(File file) {
if(file.isDirectory()) {
File[] files = file.listFiles();
for(File currFile : files) {
listDirectory(currFile);
}
}
else {
fileList.add(file.getPath());
}
}
}
The easiest way of doing that is:
File f = new File("C:\\");
ArrayList<File> files = new ArrayList<File>(Arrays.asList(f.listFiles()));
And if what you want is a list of names:
File f = new File("C:\\");
ArrayList<String> names = new ArrayList<String>(Arrays.asList(f.list()));
Have you read the API documentation for java.io.File?
File f = new File("C:\\");
File[] list = f.listFiles();
The File-class offers a listFiles()-method which returns a File
-array of all files in the current folder.
To make an ArrayList of them, you can use the Arrays-class and it's asList()-method. See here.
If you only need the file-names or paths as Strings, there is also a list()-method which returns a String-array. To convert the array to an ArrayList, follow the steps illustrated in the linked question.