import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class Main
extends Activity {
private static final String APP_TAG =
"tag";
private TextView readOutput;
@Override public void onCreate(
final Bundle icicle) {
super.onCreate(icicle);
this.setContentView(R.layout.main); readOutput = (TextView) findViewById(R.id.output); String fileName =
"test-" + System.currentTimeMillis() +
".txt"; File sdDir =
new File(Environment.getExternalStorageDirectory().getPath());
if (sdDir.exists() && sdDir.canWrite()) { File testDir =
new File(sdDir.getAbsolutePath() +
"/test_folder"); testDir.mkdir();
if (testDir.exists() && testDir.canWrite()) { File file =
new File(testDir.getAbsolutePath() +
"/" + fileName);
try { file.createNewFile(); }
catch (IOException e) { Log.e(APP_TAG,
"error creating file", e); }
if (file.exists() && file.canWrite()) { FileOutputStream fos =
null;
try { fos =
new FileOutputStream(file); fos.write(
"Hello, World!".getBytes()); }
catch (FileNotFoundException e) { Log.e(APP_TAG,
"ERROR", e); }
catch (IOException e) { Log.e(APP_TAG,
"ERROR", e); }
finally {
if (fos !=
null) {
try { fos.flush(); fos.close(); }
catch (IOException e) { } } } }
else { Log.e(APP_TAG,
"error writing to file"); } }
else { Log.e(APP_TAG,
"ERROR, unable to write to /sdcard/test_folder"); } }
else { Log.e(APP_TAG,
"ERROR, /sdcard path not available"); } File readFile =
new File(sdDir.getPath() +
"/test_folder/" + fileName);
if (readFile.exists() && readFile.canRead()) { FileInputStream fis =
null;
try { fis =
new FileInputStream(readFile);
byte[] reader =
new byte[fis.available()];
while (fis.read(reader) != -
1) { } readOutput.setText(
new String(reader)); }
catch (IOException e) { Log.e(APP_TAG, e.getMessage(), e); }
finally {
if (fis !=
null) {
try { fis.close(); }
catch (IOException e) { } } } }
else { readOutput.setText(
"Unable to read/write sdcard file, see logcat output"); } } }