-1

I've spent all day on this and need some advice!

I'm trying to save the contents of a Array List into a text file.

I have got android to save the array list contents to an internal *.txt however after entering "Test one" and "Test Two" into the array list, and a button is clicked to save the current contents into the text file. I get the following:

�� sr java.util.ArrayListx����a� I sizexp   w   t Test Onet Test Twox

An Error is also given which is:

 "File was loaded in the wrong encoding:'UTF-8'

The System.out.print gives the results:

 "I/System.out: [Test One, Test Two]" 

which is accurate to show the contents of the array list.

Code used:

public void savingfile() {
    read = (Button)findViewById(R.id.read);
    read.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            try {

                outputStream = openFileOutput(anxfile, Context.MODE_PRIVATE);

                ObjectOutputStream out = new ObjectOutputStream(outputStream);

                out.writeObject(arrayList);

                System.out.println(arrayList);

                outputStream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}

Many thanks, Leon P.S. I have tried many youtube tutorials/Stackoverflow answers to fix the problem but still having the same issue

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
Leon
  • 13
  • 1
  • 8
  • Try this, might work https://stackoverflow.com/a/47396757/1004631 – robot_alien Mar 07 '18 at 19:46
  • You are writing it out with an `ObjectOutputStream`, therefore it is serialized. You can easily read it again with an `ObjectInputStream`. But because you insist to using a `.txt` file, and somehow try to read it with utf-8 encoding (which will fail, because the java serialization format is a binary format), I believe you want just the `String`s in the `ArrayList` printed to the file. In that case, what you you want to do with it? What format do you expect? – Johannes Kuhn Mar 07 '18 at 19:51

1 Answers1

0

The list contains Strings, right?

If so, then instead of writing the object into your stream: out.writeObject(arrayList);

You may want to dig out the Strings from the List first and write them:

for (String text : arrayList) {
    out.writeObject(text);
}
Kari Sarsila
  • 232
  • 2
  • 11