13_文件的操作模式
---------------------------------------
1.注意在應用相同的情況下,不同的項目一定不要用相同的包名這樣的話,會被視為是一個應
用
----------------------------------
2.a.Context.MODE_PRIVATE:為默認操作模式,代表該文件是私有數據,只能被應用本身訪
問,在該模式下,寫入的內容會覆蓋原文件的內容,如果想把新寫入的內容追加到原文
件可以使用Context.MODE_APPEND
b.Context.MODE_PRIVATE:只可以被本應用訪問,不可以被其他應用訪問
---------------------------------
3. Unable to find instrumentation target package的問題
本例為以下DemoDao類進行單元測試
----------------新建DemoDao.java--------------
package com.neter.test.dao;
import android.util.Log;
public class DemoDao{
public void save(){
Log.i("DemoDao", "用來測試的方法");
}
}
----------------新建DemoDaoTest.java--------------
package com.neter.test.dao;
import android.test.AndroidTestCase;
import android.util.Log;
public class DemoDaoTest extends AndroidTestCase {
public void testSave() {
new DemoDao().save();
Log.i("DemoDaoTest", "測試");
}
}
-------------------------------AndroidManifest.xml--------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.neter.test.dao"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<uses-library android:name="android.test.runner"/>
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.neter.test.dao"
android:label="Testing"></instrumentation>
</manifest>
上面配置文件中
MainActivity為android程序入口,請自已新建代碼略
<uses-library android:name="android.test.runner"/>不可修改
android:name="android.test.InstrumentationTestRunner不可修改
android:label="Testing"可不寫
如出現Test run failed:Unable to find instrumentation target package
是因為 android:targetPackage="com.neter.test.dao" 必須和
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.neter.test.dao"
package相同的包名
-------------------------------------------------------------------
3.新建一個項目來測試,在
FileOutputStream outStream=context.openFileOutput(filename,Context.MODE_PRIVATE);
模式下,其他應用不可以訪問用這個模式創建的文件
-------------------------------------------------------
a.創建Android項目OherFile
b./OherFile/src/com/credream/otherfile/OherFileActivity.java 這個文件自動生成
c./OherFile/src/com/credream/othertest/AccessOtherPrivateTest.java
package com.credream.othertest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import android.test.AndroidTestCase;
import android.util.Log;
public class AccessOtherPrivateTest extends AndroidTestCase
{private static final String TAG="AccessOtherPrivateTest";
public void testAccessPrivate() throws Throwable{
String path="/data/data/com.credream.file/files/lidewei.txt";
File file=new File(path);
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
FileInputStream inputStream=new FileInputStream(file);
byte[] buffer=new byte[1024];
int len=0;
while ((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
byte[] data=outputStream.toByteArray();
outputStream.close();
inputStream.close();
String content=new String(data);
Log.i(TAG, content);
}
}
-------------------------------------------------------
d./OherFile/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.credream.otherfile"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".OherFileActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="android.test.runner" />
</application>
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.credream.otherfile" android:label="Tests for My App"
/>
</manifest>
--------------------------------------------------------
e.在AccessOtherPrivateTest.java選擇那個方法來右鍵Android junit test來測試
出現如下錯誤:
java.io.FileNotFoundException: /data/data/com.credream.file/files/lidewei.txt
(Permission denied)
at org.apache.harmony.luni.platform.OSFileSystem.openImpl(Native Method)
at org.apache.harmony.luni.platform.OSFileSystem.open(OSFileSystem.java:152)
at java.io.FileInputStream.<init>(FileInputStream.java:82)
at com.credream.othertest.AccessOtherPrivateTest.testAccessPrivate
(AccessOtherPrivateTest.java:17)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart
(InstrumentationTestRunner.java:520)
at android.app.Instrumentation$InstrumentationThread.run
(Instrumentation.java:1447)提示沒有權限
說明在模式下,其他應用無法訪問該文件;
-----------------------------------------------------
2.第二種操作模式:
Context.MODE_APPEND:模式會檢查文件是否存在,存在就往文件追加內容,否則就創建新
文件。
a.Context.MODE_APPEND:追加模式創建的文件只能被本應用訪問
---------------------------------------------------
3.小技巧:
選中字母:按ctrl+shift+y變成小寫
ctrl+shift+x變成大寫
--------------------------------------------------------------
4.選中相同部分的代碼,自動生成方法
如果相同部分代碼有很多的話,那麼可以選中重復部分的代碼,然後右鍵--->Refactor-->
Extract Mehtod-->填寫上方法名,就可以自動的生成這部分代碼的方法了
a.這個方法適用於:一個類裡面有很多方法,而每個方法裡面都有一部分這種代碼
那麼這種代碼就可以抽出來自動生成
------------------------------------------------
5.MODE_WORLD_READABLE:模式表示當前文件可以被其他應用讀取,同時如果存在這個文件
則會覆蓋原來文件的內容
--------------------------------------------------------------------
6.MODE_WORLD_WRITEABLE:表示當前文件可以被其他應用寫入。同時如果存在這個文件
則會覆蓋原來文件的內容
---------------------------------------------------------------
2013-03-06
各種文件模式的測試代碼:
----------------------------------
File項目:
------------------
/File/src/com/credream/file/readTest.java
package com.credream.file;
import com.credream.service.FileService;
import android.test.AndroidTestCase;
import android.util.Log;
public class readTest extends AndroidTestCase
{
private static final String TAG="FileServiceTest";
public void testRead()throws Exception{
FileService service=new FileService(this.getContext());
String result=service.read("lidewei.txt");
Log.i(TAG, result);
}
public void testAppend()throws Exception{
FileService service=new FileService(this.getContext());
service.saveAppend("append.txt",",www.credream.com");
}
public void testReadable()throws Exception{
FileService service=new FileService(this.getContext());
service.saveReadable("readable.txt","www.ream.com");
}
public void testWriteable()throws Exception{
FileService service=new FileService(this.getContext());
service.saveWriteable("writeable.txt","writeable");
}
}
---------------------------------------------------------------
/File/src/com/credream/service/FileService.java
package com.credream.service;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
public class FileService
{
/**
*保存文件
* @param filename 文件名稱
* @param content 文件內容
*/
private Context context;
public FileService(Context context)
{
this.context = context;
}
public void save(String filename, String content) throws Exception
{
//IO j2ee
FileOutputStream outStream=context.openFileOutput
(filename,Context.MODE_PRIVATE);
//mode:以覆蓋形式和追加形式兩種
//context.openFileOutput(filename,mode)
//Context.MODE_PRIVATE私有操作模式 創建出來的文件只能被本應用訪問
;其他應用無法訪問該文件
//另外采用私有操作模式創建的文件,寫入文件中的內容覆蓋源文件的內容
outStream.write(content.getBytes());//content.getBytes()這個方法
調用系統的
//Returns a new byte array containing the characters of this
string encoded using the system's default charset.
//默認是用utf-8
//The behavior when this string cannot be represented in the
system's default charset is unspecified. In practice, when the default charset is
UTF-8 (as it is on Android), all strings can be encoded.
//沒有默認編碼的時候,會用iso8859-1來編碼
outStream.close();
}
public void saveAppend(String filename, String content) throws Exception
{
//IO j2ee
FileOutputStream outStream=context.openFileOutput
(filename,Context.MODE_APPEND);
outStream.write(content.getBytes());//content.getBytes()這個方法
調用系統的
outStream.close();
}
public void saveReadable(String filename, String content) throws
Exception
{
//IO j2ee
FileOutputStream outStream=context.openFileOutput
(filename,Context.MODE_WORLD_READABLE);
outStream.write(content.getBytes());//content.getBytes()這個方法
調用系統的
outStream.close();
}
public void saveWriteable(String filename, String content) throws
Exception
{
//IO j2ee
FileOutputStream outStream=context.openFileOutput
(filename,Context.MODE_WORLD_WRITEABLE);
outStream.write(content.getBytes());//content.getBytes()這個方法
調用系統的
outStream.close();
}
/**
* 文件讀取內容
* @param filename 文件名
* @return
* @throws Exception
*/
public String read(String filename) throws Exception{
FileInputStream inputStream=context.openFileInput(filename);
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
//這個方法會在/data/data/<package name>/files目錄下查找這個文件
//如果找到了就返回一個輸入流
byte[] buffer=new byte[1024];
//inputStream.read(buffer);//讀滿這個數組後返回
//只要數據沒有讀完,需要一直調用這個方法
//這個方法的返回值為-1的時候,是讀完了,不是-1的時候返回的是
//讀取的大小字節
int len=0;
while ((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
//把讀取的數據放到內存中
}
byte[] data=outputStream.toByteArray();
return new String(data);
}
}
------------------------------------------------------------
/File/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.credream.file"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".FileActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="android.test.runner" />
</application>
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.credream.file" />
</manifest>
---------------------------------------------------------------
OherFile項目:
/OherFile/src/com/credream/othertest/AccessOtherPrivateTest.java
package com.credream.othertest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.test.AndroidTestCase;
import android.util.Log;
public class AccessOtherPrivateTest extends AndroidTestCase
{private static final String TAG="AccessOtherPrivateTest";
public void testAccessPrivate() throws Throwable{
String path="/data/data/com.credream.file/files/lidewei.txt";
File file=new File(path);
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
FileInputStream inputStream=new FileInputStream(file);
byte[] buffer=new byte[1024];
int len=0;
while ((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
byte[] data=outputStream.toByteArray();
outputStream.close();
inputStream.close();
String content=new String(data);
Log.i(TAG, content);
}
public void testAccessAppend() throws Throwable{
String TAG="testAccessAppend";
String path="/data/data/com.credream.file/files/append.txt";
File file=new File(path);
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
FileInputStream inputStream=new FileInputStream(file);
byte[] buffer=new byte[1024];
int len=0;
while ((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
byte[] data=outputStream.toByteArray();
outputStream.close();
inputStream.close();
String content=new String(data);
Log.i(TAG, content);
}
public void testAccessReadable() throws Throwable{
String TAG="testAccessReadable";
String path="/data/data/com.credream.file/files/readable.txt";
File file=new File(path);
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
FileInputStream inputStream=new FileInputStream(file);
byte[] buffer=new byte[1024];
int len=0;
while ((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
byte[] data=outputStream.toByteArray();
outputStream.close();
inputStream.close();
String content=new String(data);
Log.i(TAG, content);
}
public void testAccessWriteable() throws Throwable{
String path="/data/data/com.credream.file/files/writeable.txt";
File file=new File(path);www.2cto.com
FileOutputStream outputStream=new FileOutputStream(file);
outputStream.write("lidewei".getBytes());
outputStream.close();
}