Android文件读取简单操作
1 public class MainActivity extends ActionBarActivity { 2 3 final String FILE_NAME = "crazyit.bin"; 4 @Override 5 protected void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 setContentView(R.layout.activity_main); 8 9 10 System.out.println(new StringBuilder("a").append("b").append("c").toString()); 11 12 Button read = (Button) findViewById(R.id.read); 13 Button write = (Button) findViewById(R.id.write); 14 15 16 final EditText edit1 = (EditText) findViewById(R.id.edit1); 17 final EditText edit2 = (EditText) findViewById(R.id.edit2); 18 19 write.setOnClickListener(new OnClickListener() { 20 21 public void onClick(View v) { 22 write(edit1.getText().toString()); 23 edit1.setText(""); 24 } 25 }); 26 27 read.setOnClickListener(new OnClickListener() { 28 29 public void onClick(View v) { 30 edit2.setText(read()); 31 } 32 }); 33 34 } 35 36 public void write(String content){ 37 try { 38 FileOutputStream fos = openFileOutput(FILE_NAME, MODE_APPEND); 39 PrintStream ps = new PrintStream(fos); 40 ps.println(content); 41 ps.close(); 42 43 } catch (FileNotFoundException e) { 44 e.printStackTrace(); 45 } 46 47 } 48 49 public String read(){ 50 try { 51 FileInputStream fis = openFileInput(FILE_NAME); 52 byte [] buff = new byte[1024]; 53 int hasRead = 0; 54 StringBuilder builder = new StringBuilder(""); 55 while ( (hasRead = fis.read(buff)) > 0 ) { 56 builder.append(new String(buff, 0, hasRead)); 57 } 58 fis.close(); 59 return builder.toString(); 60 61 } catch (FileNotFoundException e) { 62 e.printStackTrace(); 63 } catch (IOException e) { 64 e.printStackTrace(); 65 } 66 67 return null; 68 69
xml布局文件如下: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/read" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Read" /> <Button android:id="@+id/write" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Write" /> <EditText android:id="@+id/edit1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" > <requestFocus /> </EditText> <EditText android:id="@+id/edit2" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" /> </LinearLayout>
70 }
读好书,如同与先哲们交谈。