I really new to Java so I'm having some trouble figuring this out. So basically I have a text file that looks like this:
1:John:false
2:Bob:false
3:Audrey:false
How can I create an ArrayList from the text file for each line?
Read from a file and add each line into arrayList. See the code for example.
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(<your_file_path>)))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
arr.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
While the answer above me works, here's another way to do it. Make sure to import java.util.Scanner.
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner("YOURFILE.txt");
while(scan.hasNextLine()){
list.add(scan.nextLine());
}
scan.close();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With