2016年4月14日 星期四

[Android] How-to read/write files in Android

最近要試著把儲存在Android系統手機裡面的Sqlite資料庫檔案抓出來,看儲存在裡面的資料,但因為Android系統會把自己開發的專案App檔案都放在Android系統的最內層,因此必須取得最高權限(Root)才能存取這些檔案,可是在嘗試過ADB、解除Root等方式後,還是無法取得Sqlite檔案,所以找到下面這篇詳細的文章,使用這篇文章最後一段的Read/Write to publicly readable files的方法,將資料存到記事本,然後從手機的DOWNLOAD (DIRECTORY_DOWNLOADS) 資料夾內把記事本抓出來,分析裡面儲存的資料

Read from res directory
If your application requires external file resources, you can include them in your distribution package by placing them in the res/raw folder of your project hierarchy.
To access these read-only file resources, call the openRawResource method from your application’s Resource object to receive an InputStream based on the specified file. Pass in the filename (without the extension) as the variable name from the R.raw class, as shown in the following code
Resources r = getResources();
InputStream file = r.openRawResource(R.raw.filename);

Read from assets directory
Android offers one more directory where you can keep files which also will be included in package. This directory called /assets. There are some difference from res directory.
With resources, there's built-in support for providing alternatives for different languages, OS versions, screen orientations, etc., as described here. None of that is available with assets. Also, many parts of the API support the use of resource identifiers. Finally, the names of the resources are turned into constant field names that are checked at compile time, so there's less of an opportunity for mismatches between the code and the resources themselves. None of that applies to assets.source
Context context = getApplicationContext();
InputStream is = context.getAssets().open(filename);
String text = "";

int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);

Read/Write to Internal Storage
Internal storage refers to the hard drive on device. Internal storage gives you the ability to prevent other applications from accessing the files you save and are tied directly to your app.
Files stored in /data/data/packagename/files/filename.txt. There are few modes for file access
  • MODE_PRIVATE - create a new file or overwrite one if it already exists with the same name
  • MODE_APPEND - create the file if it doesn’t exist and allow you to append to the file if it does exist
  • MODE_WORLD_READABLE - file is readable by any other application
  • MODE_WORLD_WRITEABLE - file is writeable by any other application
Write to file in internal storage
String FILE_NAME = "file.txt";
try {
    FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
    fos.write(someText.toString().getBytes());
    fos.close();
} catch (Exception e) {
    e.printStackTrace();
}
Read from file in internal storage
try {
    BufferedReader bReader = new BufferedReader(new InputStreamReader(openFileInput(FILE_NAME)));
    String line;
    StringBuffer text = new StringBuffer();                
    while ((line = bReader.readLine()) != null) {
        text.append(line + "\n");
    }
} catch (IOException e) {
    e.printStackTrace();
}

Read/Write to SDCard
External storage is typically either a removable storage media (i.e. SD Card) or an internal non-removable storage that is accessed in the same manner.
The most important thing to remember when storing files on external storage is that no security is enforced on files stored here. Any application can access, overwrite, or delete files stored on the external storage.
In order to write data to SDCard, the application need permission WRITE_EXTERNAL_STORAGE, which can be specified in the file AndroidManifest.xml.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Check external storage
private static boolean isExternalStorageReadOnly() {
    String extStorageState = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
        return true;
    }
    return false;
}

private static boolean isExternalStorageAvailable() {
    String extStorageState = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
        return true;
    }
    return false;
}
Write to SDCard
String FILE_NAME = "file.txt";
if (isExternalStorageAvailable() && isExternalStorageReadOnly()) {
    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    File file = new File(baseDir, FILE_NAME);
    FileWriter writer = null;
    try {
        writer = new FileWriter(file);
        writer.write(text.toString());
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }    
}
Read from SDCard
String FILE_NAME = "file.txt";
if (isExternalStorageAvailable() && isExternalStorageReadOnly()) {
    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    File file = new File(baseDir, FILE_NAME);

    String line = "";
    StringBuilder text = new StringBuilder();

    try {
        FileReader fReader = new FileReader(file);
        BufferedReader bReader = new BufferedReader(fReader);

        while( (line = bReader.readLine()) != null  ){
            text.append(line+"\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Read/Write to Cache
Should your application need to cache temporary files, Android offers both a managed internal cache, and (since Android API level 8) an unmanaged external cache. You can access them by calling the getCacheDirand getExternalCacheDir methods, respectively, from the current Context.
Files stored in either cache location will be erased when the application is uninstalled. Files stored in the internal cache will potentially be erased by the system when it is running low on available storage; files stored on the external cache will not be erased, as the system does not track available storage on external media.
Read from cache dir
String TMP_FILE_NAME = "tmp_file.txt";
File tmpFile;

File cacheDir = getBaseContext().getCacheDir();
tmpFile = new File(cacheDir.getPath() + "/" + TMP_FILE_NAME) ;

String line="";
StringBuilder text = new StringBuilder();

try {
    FileReader fReader = new FileReader(tmpFile);
    BufferedReader bReader = new BufferedReader(fReader);

    while( (line=bReader.readLine()) != null  ){
        text.append(line+"\n");
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}catch(IOException e){
    e.printStackTrace();
}
Write to cache dir
FileWriter writer = null;
try {
    writer = new FileWriter(tmpFile);
    writer.write(text.toString());
    writer.close();

    // path to file
    // tmpFile.getPath() 

} catch (IOException e) {
    e.printStackTrace();
}

Read/Write to publicly readable files
Android 2.2 (API level 8) includes a convenience method, Environment.getExternalStoragePublicDirectory, that can be used to find a path in which to store your application files. The returned location is where users will typically place and manage their own files of each type. This is particularly useful for applications that provide functionality that replaces or augments system applications, such as the camera, that store files in standard locations.
The getExternalStoragePublicDirectory method accepts a string parameter that determines which subdirectory you want to access using a series of Environment static constants:
  • DIRECTORY_DCIM - pictures and videos taken by the device
  • DIRECTORY_DOWNLOADS - files downloaded by the user
  • DIRECTORY_MOVIES — movies
  • DIRECTORY_MUSIC — audio fi les that represent music
  • DIRECTORY_PICTURES — pictures
Note that if the returned directory doesn’t exit, you must create it before writing fi les to the directory, as shown in the following snippet
String IMAGE_FILE_NAME = "image.png";
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(path, FILE_NAME);
try {
    path.mkdirs();
    // statements for file store
} catch (IOException e) {
    Log.d(TAG, "Error writing " + IMAGE_FILE_NAME, e);
}

*apk存放位置 C:\Users\nschenoffice\AndroidStudioProjects\Communication2-v3\app\build\outputs\apk
*That is not possible at runtime. Resources and assets are read-only at runtime.
Cite : http://en.proft.me/2014/06/21/how-readwrite-files-android/

沒有留言: