Android开发文件I/O操作示例,打开文件写入内容,然后从文件中读出显示在View上.
01 | package com.isandroid.android.simple.fileio; |
02 | import java.io.File; |
03 | import java.io.FileInputStream; |
04 | import java.io.FileOutputStream; |
05 | import java.io.IOException; |
06 | import org.apache.http.util.EncodingUtils; |
07 | import android.app.Activity; |
08 | import android.os.Bundle; |
09 | import android.util.Log; |
10 | import android.widget.TextView; |
11 | public class FileIO extends Activity { |
12 | |
13 | final String FILE_PATH = |
14 | "/data/data/com.isandroid.android.simple.fileio/" ; |
15 | final String FILE_NAME = "test.txt" ; |
16 | final String TAG = "I/O" ; |
17 | final String TEXT_ENCODING = "UTF-8" ; |
18 | |
19 | File file; |
20 | FileOutputStream out; |
21 | FileInputStream in; |
22 | TextView tv; |
23 | String display; |
24 | /** Called when the activity is first created. */ |
25 | @Override |
26 | public void onCreate(Bundle savedInstanceState) { |
27 | super .onCreate(savedInstanceState); |
28 | try { |
29 | //创建文件 |
30 | file = new File(FILE_PATH , FILE_NAME); |
31 | file.createNewFile(); |
32 | |
33 | //打开文件file的OutputStream |
34 | out = new FileOutputStream(file); |
35 | String infoToWrite = "面朝大海,春暖花开." ; |
36 | //将字符串转换成byte数组写入文件 |
37 | out.write(infoToWrite.getBytes()); |
38 | //关闭文件file的OutputStream |
39 | out.close(); |
40 | |
41 | //打开文件file的InputStream |
42 | in = new FileInputStream(file); |
43 | //将文件内容全部读入到byte数组 |
44 | int length = ( int )file.length(); |
45 | byte [] temp = new byte [length]; |
46 | in.read(temp, 0 , length); |
47 | //将byte数组用UTF-8编码并存入display字符串中 |
48 | display = EncodingUtils.getString(temp,TEXT_ENCODING); |
49 | //关闭文件file的InputStream |
50 | in.close(); |
51 | } catch (IOException e) { |
52 | //将出错信息打印到Logcat |
53 | Log.e(TAG, e.toString()); |
54 | this .finish(); |
55 | } |
56 | |
57 | //将读出的字符串用TextView显示到主界面 |
58 | tv = new TextView( this ); |
59 | tv.setText(display); |
60 | setContentView(tv); |
61 | } |
62 | } |