android 把数据保存到文件中的实例

xiaoxiao2021-02-28  20

/** * 把字符串写入文件 * @param data * @param fileName */ public void writeDataToFile(String data,String fileName) { FileOutputStream out; BufferedWriter writer = null; String Path = Const.path + "/" + fileName + ".xml"; File file = new File(Path); try { /** * Context().openFileOutput(name,mode)方法指定路径创建文件并写入, * 只能传入文件名不能传入路径即不能包含"/" * Context.MODE_APPEND:会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。 * Context.MODE_PRIVATE:写入的内容会覆盖原文件的内容 */ // out = MyApplication.getContext().openFileOutput(fileName, MODE_PRIVATE); // out = MyApplication.getContext().openFileOutput(fileName, MODE_APPEND); /** * FileOutputStream(name,append) * 可传入文件路径,把数据写入指定路径指定文件; * 若只传入参数name,写入内容会覆盖原文件的内容; * 若增加传入参数append,且为true,则往文件追加内容; */ out = new FileOutputStream(file,true); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(data); } catch (Exception e ) { e.printStackTrace(); Log.e(Tag,"写入文件失败"); } finally { try { if (writer != null) { writer.close(); } }catch (IOException e) { e.printStackTrace(); Log.e(Tag,e.getMessage()); } } }  
转载请注明原文地址: https://www.6miu.com/read-2602782.html

最新回复(0)