[英]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
例如,我在文件夹中有两个CSV文件,需要逐行从一个文件中读取数据,并将其存储在数组列表
A
例如文件2动态地存储到数组列表B
。也就是说,如果有3个文件,则应将其存储在数组中清单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循环中。
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
. 虽然阵列上迭代,你通常做迭代从
0
到length - 1
不是0
到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. 现在,您将从该文件所在的
D:\\April\\
目录中获取文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.