ArrayList<String> list = new ArrayList<String>();
Scanner inFile = null;
try {
inFile = new Scanner(new File("textfile.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(inFile.hasNextLine()){
list.add(inFile.nextLine());
}
Read file to Array then store Array into ArrayList Java
Question
How's it going everyone. I am trying to read a file and store each String within that file into an element in the Array. The problem is, I cannot move to the next line of data. I am assuming that is when I would need to use an ArrayList, but I am having difficulty figuring out how to iterate through each text on each line and store that into an element then move on to the next line. I want to have each data stored in its own element. Also how would I call the data stored within that element? Here is my code:
Scanner readPayrollData = new Scanner(new FileReader ("employeeData.dat"));
String[] employee = new String[3];
ArrayList<String> data = new ArrayList<String>();
while(readPayrollData.hasNextLine())
{
for(int i = 0; i < employee.length; i++)
{
readPayrollData.hasNext();
employee[i] = readPayrollData.next();
}
readPayrollData.hasNextLine();
data.add(employee);
}
System.out.println(data);
readPayrollData.close();
La solution
Autres conseils
List<String> employee=new ArrayList<>();
Scanner fin=null;
try{
fin=new Scanner(new File("employeeData.dat"));
}catch(Exception e){
System.out.println("unable to open file");
e.printStackTrace();
}
while(fin.hasNextLine()){
employee.add(fin.nextLine());
}
fin.close();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow