Android 文件的讀取和寫入


(1)openFileInput和openFileOutput的使用

文件的使用,注意最后要用finally給關閉掉。

openFileOutput:(寫入文件,如果沒有文件名可以創建,這里不需要判斷是否有這個文件)---> FileOutputStream
openFileInput:(讀取文件,沒有文件名會保存,debug的時候會看到,不影響ui)---> FileInputStream

    保存文件:(FileOutputStream 保存地址;data/data/包名/files/, 下面是寫入的四種模式)
    MODE_APPEND:即向文件尾寫入數據
    MODE_PRIVATE:即僅打開文件可寫入數據
    MODE_WORLD_READABLE:所有程序均可讀該文件數據
    MODE_WORLD_WRITABLE:即所有程序均可寫入數據。

    private void savePackageFile() {
        String msg = tvSaveMessage.getText().toString() + " \n";
        FileOutputStream outputStream;

        try {
            outputStream = openFileOutput(filename, Context.MODE_APPEND);
            outputStream.write(msg.getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    讀取文件:(FileInputStream 讀取包名下files文件夾下的文件)
    private void readSaveFile() {
        FileInputStream inputStream;

        try {
            inputStream = openFileInput(filename);
            byte temp[] = new byte[1024];
            StringBuilder sb = new StringBuilder("");
            int len = 0;
            while ((len = inputStream.read(temp)) > 0){
                sb.append(new String(temp, 0, len));
            }
            Log.d("msg", "readSaveFile: \n" + sb.toString());
            inputStream.close();

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

    文件的初始化:(創建需要的文件)
    File logFile = new File(context.getFilesDir(), MainActivity.filename);
    // Make sure log file is exists
    if (!logFile.exists()) {
        boolean result; // 文件是否創建成功
        try {
            result = logFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        if (!result) {
            return;
        }
    }
  • 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
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

(2)BufferReader和BufferWriter使用:

保存文件:如果沒有會自動創建,如果有的話會覆蓋。 當在創建時加入true參數,回實現對文件的續寫。 false則會覆蓋前面的數據
public static void bufferSave(String msg) {
    try {
        BufferedWriter bfw = new BufferedWriter(new FileWriter(logFile, true));
        bfw.write(msg);
        bfw.newLine();
        bfw.flush();
        bfw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

讀取文件:這里需要做判斷,如果沒有這個文件會報錯。
public static void bufferRead() {
    try {
        BufferedReader bfr = new BufferedReader(new FileReader(logFile));
        String line = bfr.readLine();
        StringBuilder sb = new StringBuilder();
        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = bfr.readLine();
        }
        bfr.close();

        Log.d("buffer", "bufferRead: " + sb.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 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

(3)SD卡讀取和寫入—路徑:/storage/sdcard0/ 
SD卡權限;

<!-- 在SDCard中創建與刪除文件權限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard寫入數據權限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

往SD卡寫入文件的方法
public void savaFileToSD(String filename, String filecontent) throws Exception {
    //如果手機已插入sd卡,且app具有讀寫sd卡的權限
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
   filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;

        //這里就不要用openFileOutput了,那個是往手機內存中寫數據的
        FileOutputStream output = new FileOutputStream(filename);
        output.write(filecontent.getBytes());
        //將String字符串以字節流的形式寫入到輸出流中
        output.close();
        //關閉輸出流
    } else Toast.makeText(context, "SD卡不存在或者不可讀寫", Toast.LENGTH_SHORT).show();
}

//讀取SD卡中文件的方法
//定義讀取文件的方法:
public String readFromSD(String filename) throws IOException {
    StringBuilder sb = new StringBuilder("");
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
        //打開文件輸入流
        FileInputStream input = new FileInputStream(filename);
        byte[] temp = new byte[1024];

        int len = 0;
        //讀取文件內容:
        while ((len = input.read(temp)) > 0) {
            sb.append(new String(temp, 0, len));
        }
        //關閉輸入流
        input.close();
    }
    return sb.toString();
}
  • 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
  • 40
  • 41

(4)讀取raw和assets文件夾下的文件

res/raw:文件會被映射到R.java文件中,訪問的時候直接通過資源ID即可訪問,而且 他不能有目錄結構,就是不能再創建文件夾
assets:不會映射到R.java文件中,通過AssetManager來訪問,能有目錄結構,即, 可以自行創建文件夾

讀取文件資源;

raw: 
InputStream is =getResources().openRawResource(R.raw.filename);  

assets: 
AssetManager am =  getAssets();   
InputStream is = am.open("filename");

這里已經寫完了,后續會持續更新文章...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM