January 2013
Intermediate to advanced
408 pages
9h 23m
English
If the data you want to preserve cannot be best represented as key/value pairs, then you might want to use the primitive method of saving it directly to the filesystem as files. This option is useful for saving long strings of text, or binary data.
To create a file for saving, you can use the openFileOutput() method, specifying the filename and the mode in which you want the file to be opened. This method will then return a FileOutputStream object:
package net.learn2develop.files;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//---writing to files---
try {
FileOutputStream fOut =
openFileOutput("textfile.txt", MODE_PRIVATE);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
For writing bytes to a file, use the OutputStreamWriter class and use its write() method to write a string to the file. To save the changes to the file, use its close() method:
package net.learn2develop.files; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import android.app.Activity; import android.os.Bundle; import android.widget.Toast; ...Read now
Unlock full access