0

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?

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

Either you can parse the string and convert it to an Array using iteration or you can use a library that will do it for you.

I would recommend using Jackson, you can find an easy tutorial here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.