Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?
As an exercise, I would suggest doing the following:
public void save(String fileName) throws FileNotFoundException {
PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
for (Club club : clubs)
pw.println(club.getName());
pw.close();
}
This will write the name of each club on a new line in your file.
Soccer
Chess
Football
Volleyball
...
I'll leave the loading to you. Hint: You wrote one line at a time, you can then read one line at a time.
Every class in Java extends the Object
class. As such you can override its methods. In this case, you should be interested by the toString()
method. In your Club
class, you can override it to print some message about the class in any format you'd like.
public String toString() {
return "Club:" + name;
}
You could then change the above code to:
public void save(String fileName) throws FileNotFoundException {
PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
for (Club club : clubs)
pw.println(club); // call toString() on club, like club.toString()
pw.close();
}
How to read and write Java ArrayList Objects to and from a file that has a specific required structure
In your example you use serialization (you can read more about it here Introduction to Java Serialization), which saves an object to a file in binary format. So basically you're saving the whole ArrayList
, including its internal fields and values as an array of bytes.
But what you really need is simply writing to a text file.
Here's one of the ways you can do that using java.io.PrintWriter
:
PrintWriter p = new PrintWriter("reservations.txt");
p.write("your text goes here");
And yes, you have to prepare the text for writing manually.
In your case the best approach would be overriding toString()
method of Passenger
class, so you can write to a file as simply as this:
Passenger p1 = new Passenger(0001, "John Smith", "1A", "AA12");
Passenger p2 = new Passenger(0002, "Annah Smith", "1B", "AA12");
p.write(p1.toString());
p.write(p2.toString());
toString()
method has to concatenate required fields(ID, Name, SeatNumber, Flight#) and return them as a single String
with a TAB character as a delimiter.
Java reading a file into an ArrayList?
This Java code reads in each word and puts it into the ArrayList:
Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next());
}
s.close();
Use s.hasNextLine()
and s.nextLine()
if you want to read in line by line instead of word by word.
Load an ArrayList with nested ArrayLists from a file using Java
Read the file contents, split by line separator and then remove the brackets and split again to get the list items. Something like
File file = new File("path/to/the/text/file");
FileReader reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
String fileContent = new String(chars);
ArrayList<ArrayList<String>> readList = new ArrayList<>();
String[] splittedArr = fileContent.split(System.lineSeparator());
for(String list : splittedArr) {
list = list.replace("[", "").replace("]", ""); //removing brackets as the file will have list as [a, b, c]
List<String> asList = Arrays.asList(list.split(", "));//splitting the elements by comma and space
readList.add(new ArrayList<>(asList));
}
reader.close();
How to read file into an Arraylist and print the ArrayList in Java
The Correct Syntax for Scanner :
Scanner s = new Scanner(new File("A.txt") );
In java Object is the superclass of all the classes ie. predefined sucs as String or any user defined .
It will accepts any kind of data such as string or any other types contained in the A.txt file.
========================================================================
import java.io.*;
import java.util.*;
class B{
public static void main(String aregs[]) throws FileNotFoundException {
Scanner s = new Scanner(new File("A.txt") );
ArrayList<Object> list = new ArrayList<Object>();
while(s.hasNext()) {
list.add(s.next());
}
System.out.println(list);
}
}
How to save Each index of Array List in text file as new line in java?
As both the save operations are on the same thread the lines would be written to the file in a synchronous manner. So after reading all the lines from the file we can split the lines based on the size of the input lists i.e. the first set of values would have been inserted by the 'First' list.
public void ReadFromText() {
// Read from Text file and save in both lists
List<Integer> output1 = new ArrayList<>();
List<Integer> output2 = new ArrayList<>();
try {
Path path = Path.of("D:\\Sample.txt");
List<String> inputList = Files.lines(path).collect(Collectors.toList());
for (int i = 0; i < inputList.size(); i++) {
String s = inputList.get(i);
if (!s.isEmpty()) {
if (i < First.size()) {
output1.add(Integer.valueOf(s));
} else {
output2.add(Integer.valueOf(s));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Writing and Reading to/from a file Objects stored in ArrayList
Here you go... please take note of the following:
YES, Chetan Jadhav CD's suggestion WORKS. B
Use an IDE like Eclipse to help you debug your code and make your life easier.
Be clear about what your error is (show stack trace, etc..) Note the modification to your catch clause that prints:
System.out.println("Saving ERROR: " + ex.getMessage());
Put all your code in one file before you ask for help to make everyone's life easier.
Make each 'Person' at least someone unique by numbering them with your index Use .ser for a serializable file, rather than .dat
import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class Data {
private static final String SER_FILE = "C:\\view\\data.ser";
static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
Data.savePersons();
Data.loadPersons();
}
public static void savePersons() throws IOException {
/** Make 5 'Person' object for example */
for (int i = 0; i < 5; i++) {
Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890-" +i);
persons.add(personTest);
}
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SER_FILE, true));) {
oos.writeObject(persons);
System.out.println("Saving '" + persons.size() + "' Object to Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR: " + ex.getMessage());
}
}
public static void loadPersons() throws IOException {
/** Clean 'persons' array for TEST of load data */
persons.removeAll(persons);
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SER_FILE));){
persons = (List<Person>) ois.readObject();
//persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" + persons.size() + "' Object from Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("loadPersons() = OK");
persons.stream().forEach(System.out::println);
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR: " + e.getMessage());
}
}
}
class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String surname;
private String mail;
private String telephone;
public Person(String n, String s, String m, String t) {
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}
@Override
public String toString() {
return "Person [name=" + name + ", surname=" + surname + ", mail=" + mail + ", telephone=" + telephone + "]";
}
}
Reading a text file & adding the content to an ArrayList
Using Java 7 & Java 8 API's feature, you can solve your problem like below:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class LineOperation {
private static List<String> lines;
public static void main(String[] args) throws IOException {
lines = Collections.emptyList();
try {
lines = Files.readAllLines(Paths.get("C:\\Users\\Abhinav\\Downloads\\TempData2018a.txt"), StandardCharsets.UTF_8);
String stationName = lines.get(0);
String[] arr = null;
ArrayList<StationRecord> data = new ArrayList<>();
for(int i=1;i<lines.size();i++) {
arr = lines.get(i).split(" ");
data.add(new StationRecord(Long.parseLong(arr[0]), Integer.parseInt(arr[1]), Integer.parseInt(arr[2]), Integer.parseInt(arr[3]), Double.parseDouble(arr[4])));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
But I strongly recommend you to refer below links for your further clarifications on Java I/O:-
Java – Read from File
Read a File into an ArrayList
Related Topics
Java Regex to Validate Full Name Allow Only Spaces and Letters
How to Check Json in Response Body With Mockmvc
Java.Lang.Illegalargumentexception: Not a Managed Type: Class
How to Get Numbers from Given Gcd and Lcm
Spring Boot/Spring Kafka Ssl Configuration by Environment Variables Impossible
Testing @Postconstruct With Mockito
@Autowired - No Qualifying Bean of Type Found for Dependency
Javax.Xml.Bind.Unmarshalexception: Unexpected Element (Uri:"", Local:"Group")
Java 8 Streams: Multiple Filters Vs. Complex Condition
Alternative to Switch Case in Java
How to Handle JPA Unique Constraint Violations
Java Stream Collectors.Groupingby() Multiple Fields
Spring Data JPA and Parameters That Can Be Null
How to Download Entire Folder Located on S3 Bucket
String.Replaceall Single Backslashes With Double Backslashes
How to Solve Liquibase Checksum Validation Fail After Liquibase Upgrade
How to Have Empty Requestparam Values Use the Defaultvalue
How to Query Using an Enum Parameter Mapped as Ordinal Using JPA and Hibernate