Skip to content
Advertisement

Load an ArrayList with nested ArrayLists from a file using Java

I have an arraylist like ArrayList<ArrayList<String>>. I have saved my main ArrayList in a text file by using the following code.

 ArrayList<ArrayList<String>> ar2 = new ArrayList<>();
 FileWriter writer = new FileWriter("path/to/the/text/file");
        for(ArrayList<String> str: ar2) {
            writer.write(str + System.lineSeparator());

        }
        writer.close();

Now, I want to load the saved data from the file to the same ArrayList ar2 in every new run. I tried several methods but the nested arraylists are loaded as Strings. How can I overcome from this issue?

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement