android文件存儲:直接存儲文件和文件存儲到SDCard

之前我們的內容是存在手機自帶的存儲空間裏的,但是我們知道手機自帶的存儲空間比較小,如果我們要存儲的內容,比如說視頻佔空間很大,我們就必須得將大文件存入SDCard。

1.直接存儲,文件存入/data/data/<package name>/files目錄下

FileService.java   保存文件方法代碼

1
2
3
4
5
6
7
//直接存儲文件

 public void save(String fileName, String content) throws Exception {

        //文件輸出流

        FileOutputStream fos;
        fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
        fos.write(content.getBytes());
        fos.close();
    }

單元測試存儲:

1

FileService  service=new FileServie();

service.save("aa.txt", "sfdgdhfh");

存儲成功後的aa文件存到data/data/項目/files下的aa.txt,導出文件查看內容是:sfdgdhfh

 

2.存入SDCard

         用戶輸入文件名及內容點擊保存按鈕存儲到SDCard

        佈局代碼:

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
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="fill_parent"
     android:layout_height="match_parent"
     android:orientation="vertical" >
                                                            
     <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="文件名稱"
         tools:context=".MainActivity" />
                                                            
     <EditText
         android:id="@+id/filename"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:inputType="text" />
                                                            
     <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="文件內容" />
                                                            
     <EditText
         android:id="@+id/content"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:gravity="top"
         android:minLines="4"
         android:inputType="textMultiLine" />
                                                            
     <Button
         android:id="@+id/save"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="保存"
         tools:context=".MainActivity" />
                                                            
 </LinearLayout>

編寫業務類FileService,實現存儲功能saveToSDCard()及讀文件readFile()

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
public class FileService {
    private Context context;
                                                    
    public FileService(Context context) {
        super();
        this.context = context;
    }
    public void saveToSDcard(String filename, String content) throws IOException{
       //創建文件file及得到外部存儲設備絕對路徑
       File file=new File(Environment.getExternalStorageDirectory(),filename);
       //文件輸出流
       FileOutputStream fos=new FileOutputStream(file);
       //通過文件輸出流寫入文件內容
       fos.write(content.getBytes());
       fos.close();
    }
                                                      
    // 讀文件
    public String readFile(String filename) throws IOException {
        FileInputStream fis = context.openFileInput(filename);
        int len = 0;
        byte[] buffer = new byte[1024];
        // 往內存中輸出數據
        //另一種輸出方式  StringBuffer sbuffer=new StringBuffer();
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        while ((len = fis.read(buffer)) != -1) {
            //sbuffer.append(buffer);
            outstream.write(buffer, 0, len);
        }
        // 得到內存中數據以二進制存放
        byte[] s=outstream.toByteArray();     
        outstream.close();
        fis.close();
        return new String(s); 
    }
 }

編寫測試類測試存儲方法是否有錯誤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class FileServiceTest extends AndroidTestCase {
    FileService service = new FileService(getContext());
    public void testSaveToSDcard() {
        try {
            service.saveToSDcard("b.txt", "文件存儲到SDCard,真好");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
                                               
    public void testReadFile() {
        try {
            System.out.println(service.readFile("b.txt"));
        } catch (IOException e) {
            e.printStackTrace();
        }
                                                      
    }
                                               
 }

單元測試應配置一些屬性

1
2
<!-- 單元測試庫的配置 -->
         <uses-library android:name="android.test.runner" />
1
2
3
4
5
<!-- 單元測試 -->
     <instrumentation
         android:name="android.test.InstrumentationTestRunner"
         android:targetPackage="cn.bzu.filefro" >
     </instrumentation>

Activity代碼

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
public class MainActivity extends Activity {
    private EditText filename;
    private EditText content;
    private Button save;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       filename=(EditText) this.findViewById(R.id.filename);
       content=(EditText) this.findViewById(R.id.content);
        save=(Button) this.findViewById(R.id.save);
        save.setOnClickListener(new View.OnClickListener() {
                                             
            public void onClick(View v) {
                String file=filename.getText().toString();
                String filecontent=content.getText().toString();
                FileService service=new FileService(MainActivity.this);
                try {
                    service.saveToSDcard(file, filecontent);
                    System.out.println(service.readFile(file));
                    Toast.makeText(MainActivity.this, file+"存儲成功\n內容是:"+filecontent, Toast.LENGTH_LONG).show();
                                                     
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}


效果圖




 

文件存儲到mnt/sdcard/下


導出hello內容是:

大家好,見到你們很高興,嘿嘿。希望以後相處融洽。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章