Android-Context的IO功能,android-contextio

來源:互聯網
上載者:User

Android-Context的IO功能,android-contextio

  如何將應用資料儲存到本地檔案?如何從本地檔案載入資料到應用中?我實現的步驟是:

  應用(java資料)<--org.json-->JSONString<--Context.IO-->本地檔案

  今天向讀者講解的是Context.IO部分。

File getDir(String name, int mode)

擷取/data/data/<packagename>/目錄的子目錄(如不存在就先建立
它)

File getFilesDir() 擷取/data/data/<packagename>/files目錄
File getCacheDir()

擷取/data/data/<packagename>/cache目錄。應注意及時清理該目錄,並節約使用空間

String[] fileList()

擷取/data/data/<packagename>/files目錄下的檔案清單。可與其他方
法配合使用,例如openFileInput(String)

FileInputStream openFileInput(String name) 開啟現有檔案進行讀取

FileOutputStream openFileOutput(String
name, int mode)

開啟檔案進行寫入,如不存在就建立它

 

 

 Context.IO實現本地檔案的字串輸入輸出

public class SerializerUtils {                public static void save(Context c,String fileName,String data) throws IOException{        Writer writer=null;        try{        OutputStream out=c.openFileOutput(fileName, Context.MODE_PRIVATE);        writer=new OutputStreamWriter(out);        writer.write(data);        }finally{            if(writer!=null){                writer.close();            }        }    }        public static String load(Context c,String fileName)throws IOException{        StringBuilder data=new StringBuilder();        BufferedReader reader=null;        try{            InputStream in=c.openFileInput(fileName);            reader=new BufferedReader(new InputStreamReader(in));            String line=null;            while((line=reader.readLine())!=null){                data.append(line);            }        }finally{            if(reader!=null){                reader.close();            }        }        return data.toString();    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.