NikanDalvand NikanDalvand - 2 months ago 5
Java Question

Reading and writing an array to file

Hello there stackoverflow .
The thing im tring to make work is saving some information from an array to a file and then reading it back to another array . The goal is to save themes (hex color codes of user) so they can share their theme or backing it up .
Here is my code to write the array to file

String filename = "my.theme";
String[] numbers = new String[] {"1, 2, 3"};
FileOutputStream outputStream;

try {
outputStream = openFileOutput(filename, Context.MODE_APPEND);
for (String s : numbers) {
outputStream.write(s.getBytes());
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}


The output is a file with :

1,2,3


Now how can i read it back to another array ?
For my goal . Can you suggest anything other then using this method ? Its ok to save as a xml too . Thanks :)

Answer

You can use a Scanner class, this small example will help you get started:

String input = "1,2,3";
Scanner scn = new Scanner(input);  // Scanner also accepts a file!
scn.useDelimiter(","); // Since the integers are "comma" separated.
while(scn.hasNext())
{
    System.out.println(scn.nextInt()); // here you can store your integers back into your array
}
scn.close();

OUTPUT:

1
2
3
Comments