Reputation: 3
For example, I have two CSV files in folder and need to read data from one file line by line, and store it in array list A
like file 2 to array list B
dynamically.. i.e. if there is 3 file it should store in array list C
public class DashboardReport
{
public static void main(String[] args)
{
int count = 0;
String line = "";
File folder = new File("D:/April");
File[] listOfFiles = folder.listFiles();
System.out.println("Count" + listOfFiles.length);
count = listOfFiles.length;
List books = new ArrayList();
for (int i = 0; i <= listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
System.out.println("File " + listOfFiles[i].getName());
Path pathToFile = Paths.get(listOfFiles[i].getName());
try (BufferedReader br = Files.newBufferedReader(
pathToFile, StandardCharsets.US_ASCII))
{
line = br.readLine();
String[] attributes = {};
while (line != null)
{
attributes = line.split(",");
books.add(attributes);
line = br.readLine();
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
else if (listOfFiles[i].isDirectory())
{
System.out.println("Directory " + listOfFiles[i].getName());
}
}
}
}
Upvotes: 0
Views: 126
Reputation: 11950
You have two errors here. One is in the for loop.
for (int i = 0; i <= listOfFiles.length; i++)
^
While iterating on an array, you'd normally do iterate from 0
to length - 1
not 0
to length
.
Then the second one is you are not taking the path into account, only the filename.
Path pathToFile = Paths.get(listOfFiles[i].getName());
^
This searches for a file with the same name, but in the current working directory, and as usual, it won't be found. Change it to use the absolute path instead.
Path pathToFile = Paths.get(listOfFiles[i].getAbsolutePath());
Now you will be getting the file from that D:\April\
directory, where your file does exist.
Upvotes: 1