Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get contents of a folder and put into an ArrayList

Tags:

java

file

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 readers, so please tell me if that is better.

Here's the code I have so far:

import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException;   public class buffered_read { public static void main(String[] args) {     File f = new File("C:\\");     int x = 0;     boolean b = true;     File list[];     while(b = true){      } } } 

Thanks, obiedog

like image 874
Obiedog Avatar asked Sep 04 '11 19:09

Obiedog


People also ask

How do you read a file and store it to an ArrayList in Java?

This Java code reads in each word and puts it into the ArrayList: Scanner s = new Scanner(new File("filepath")); ArrayList<String> list = new ArrayList<String>(); while (s. hasNext()){ list.

How do I copy a list into an ArrayList?

Constructor A simple way to copy a List is by using the constructor that takes a collection as its argument: List<Plant> copy = new ArrayList<>(list); Since we're copying references here, and not cloning the objects, every amends made in one element will affect both lists.

How do you import a text file into an ArrayList?

All you need to do is read each line and store that into ArrayList, as shown in the following example: BufferedReader bufReader = new BufferedReader(new FileReader("file. txt")); ArrayList<String> listOfLines = new ArrayList<>(); String line = bufReader. readLine(); while (line !


1 Answers

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())); 
like image 150
user927911 Avatar answered Oct 08 '22 15:10

user927911