简体   繁体   中英

Reading data from file and store it in Array list

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.. ie 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());
            }
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM