InternalFileWriteReadActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.LinearLayout; import android.widget.TextView; import course.examples.Files.FileWriteAndRead.R; public class InternalFileWriteReadActivity extends Activity { private final static String fileName = "TestFile.txt"; private String TAG = "InternalFileWriteReadActivity"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout); // Check whether fileName already exists in directory used // by the openFileOutput() method. // If the text file doesn't exist, then create it now if (!getFileStreamPath(fileName).exists()) { try { writeFile(); } catch (FileNotFoundException e) { Log.i(TAG, "FileNotFoundException"); } } // Read the data from the text file and display it try { readFile(ll); } catch (IOException e) { Log.i(TAG, "IOException"); } } private void writeFile() throws FileNotFoundException { FileOutputStream fos = openFileOutput(fileName, MODE_PRIVATE); PrintWriter pw = new PrintWriter(new BufferedWriter( new OutputStreamWriter(fos))); pw.println("Line 1: This is a test of the File Writing API"); pw.println("Line 2: This is a test of the File Writing API"); pw.println("Line 3: This is a test of the File Writing API"); pw.close(); } private void readFile(LinearLayout ll) throws IOException { FileInputStream fis = openFileInput(fileName); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line = ""; while (null != (line = br.readLine())) { TextView tv = new TextView(this); tv.setTextSize(24); tv.setText(line); ll.addView(tv); } br.close(); } } |
main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scrollView1" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > </LinearLayout> </ScrollView> |