Reputation: 681
EDIT: While following up on the two suggestions I determined that the following would work for writing the Strings to a file as Byte arrays. But now I need to figure out how to read the Byte arrays back into Strings. I could use help with that please... Is there a FileInputStream component that is the reverse equivalent of this FileOutputStream? This works for writing the Strings as Byte arrays.
try {
FileOutputStream fos = openFileOutput("stack.txt", Context.MODE_PRIVATE);
for (String item : stack)
fos.write(stack.pop().getBytes());
fos.close();
sb.append("The Stack is saved.\n");
} catch (IOException e) {
sb.append(e.toString());
}
displayText(sb.toString());
I am trying to write Strings from an ArrayDeque to a file. I am using the ArrayDeque as a Stack. The strings are of varying length. I get this error on opening the file for output...
java.io.FileNotFoundException: stack.txt: open failed: EROFS (Read-only file system)
I think I have seen all of the posts on this topic but with no help. My two code snippets are:
root = new File(getExternalFilesDir(null), "/HTMLSpyII/");
if (!root.exists()) {
if (!root.mkdirs()) {
runTimeAlert("File path does not exist or\n" +
"Unable to create path \n" + root.toString());
}
}
try {
DataOutputStream dos = new DataOutputStream(
new FileOutputStream("stack.txt")); // program fails here
for (String item : stack)
dos.writeUTF(stack.pop());
dos.close();
sb.append("The Stack is saved.\n");
} catch (IOException e) {
sb.append(e.toString());
}
displayText(sb.toString());
I have parallel code for reading them back using DataInputStream with FileInputStream. I am missing something. Is it perhaps some initial preparation before creating the file?
Doing some research I have a feeling that the problem may be that I am not yet familiar with the requirements for using the new app-specific, persistent, internal/external storage? But I do not know so I am looking for some guidance, please :)
Upvotes: 0
Views: 1014
Reputation: 681
This is the outline of a complete solution to the problem. Hope this helps someone, sometime...
The problem is: To use an ArrayDeque as a Stack for saving Strings, and use a file for Save and Restore of the stack.
The key parts of the solution are: to use ObjectOutputStream and ObjectInputStream for saving and restoring the stack to external storage. to use getExternalFilesDir() to open the file for save and for restore.
To open the file for Saving the current stack contents...
File stackRoot = new File(getExternalFilesDir(null), "/AppName/stack.dat");
FileOutputStream fos = new FileOutputStream(stackRoot);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for (String item : stack) oos.writeObject(item);
oos.close();
File stackRoot = new File(getExternalFilesDir(null), "/AppName/stack.dat");
FileInputStream fis = new FileInputStream(stackRoot);
ObjectInputStream ois = new ObjectInputStream(fis);
while (true) stack.addLast((String) ois.readObject());
Upvotes: 1